# Sum of Digits in C program

In this program, we take input from the user and find the sum of digits in c using for loop and while loop. for example, the sum of digits of 123 is 1+2+3=6

## Sum of Digits of a number in C using for loop

take the number from the user, divide the number into individual digits, and adding those individuals (Sum) digits using for Loop

``````#include<stdio.h>
int main()
{
int sum=0,n,r,i;
printf("\n enter the number:");
scanf("%d",&n);
for(i=n;i>0;i=i/10)
{
r=i%10;
sum+=r;
}
printf("\n sum of digit=%d",sum);
return 0;
}  ``````

Reduce the number of line of code by writing for loop in these ways

``````for(i=n;i>0;sum+=i%10,i=i/10) {
}``````

## output

```enter the number:123
sum of digit=6```

## C program to print sum of digit using while loop

take the number from the user, divide the number into individual digits, and adding those individuals digits using for Loop

``````#include<stdio.h>
int main()
{
int r,n,sum=0;
printf("enter the number:");
scanf("%d",&n);
while(n>0)
{
r=n%10;
sum=sum+r;
n=n/10;
}
printf("\n sum of digit=%d",sum);
return 0;
} ``````

## output

```enter the number:156
sum of digit=12```

### Logic to find sum of digits in C

1. take the number from the user and store it in a variable `n`.
2. Find the last digits using modulus division `r=n%10`.
3. Add the last digit into variable `sum`.
4. repeat step 2 and 3 until the value of n become 0.