# Sum of Digits of a Given Number in C

The sum of digits in C can be written using loops. To find the sum of the digits of a given number we need to follow below procedures,

1) Take a number as input
2) Declare two variables `lastDigit` and sum and initialize the sum variable with 0
3) Find the last digit of the number, `lastDigit` = number%10
4) Add the value of `lastDigit` to the variable sum
5) Remove the last digit of the number. number = number/10
6) Repeat 3 to 5 steps until the number does not becomes 0.

Prerequisites:- While loop in C, For loop in C

The sum of digits of the number 54321 = 5+4+3+2+1 = 15

## Sum of Digits in C using the while loop

`````` #include<stdio.h>
int main()
{
int number,lastDigit,sum=0;

printf("Enter any number: ");
scanf("%d",&number);

while(number!=0)
{
lastDigit=number%10;
sum += lastDigit;
number/=10;
}

printf("Sum of digits =  %d\n",sum);

return 0;
}``````

Output:-

Enter any number: 123456
Sum of digits = 21

The statements of the while loop also can be written in two-line as given below. In this case, the variable `lastDigit` is not required.

`````` while(number!=0)
{
sum += (number%10);
number/=10;
}``````

## Using for loop

`````` #include<stdio.h>
int main()
{
int number,sum;

printf("Enter any number: ");
scanf("%d",&number);

for(sum = 0; number!=0; number/=10)
{
sum += (number%10);
}

printf("Sum of digits =  %d\n",sum);

return 0;
}``````

Output:-

Enter any number: 125
Sum of digits = 8

From for loop in the C language topic, we know that we can write more than one update expression inside the `for` loop. So, in above program we can reduce the number of lines of for loop. Don’t forget the semicolon at the end of the `for `loop.

``for(sum = 0; number!=0; sum += (number%10), number/=10);``

## Sum of Digits in C without using a loop

In this case. we can use a recursive function to find the sum of digits of a given number.

`````` #include<stdio.h>
int sumOfDigits(int n)
{
if(n==0) return 0;
else return (n%10)+sumOfDigits(n/10);
}
int main()
{
int number, sum;

printf("Enter any number: ");
scanf("%d",&number);

sum = sumOfDigits(number);

printf("Sum of digits =  %d\n",sum);

return 0;
}``````

In this program, we developed a recursive function `sumOfDigits()`, this function finds the sum of the digits of a given number by the recursive way. A function that calls itself is called the recursive function. Recursion is one the way to find the solution to the program.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!