C Sum of n Digits

Here your task is to add n digits of a number for one time i.e) if user entered 786 you have to reply 18 which means 7 + 8 + 6.

C Program - To Sum n Digits

Let us write a c program to sum n digits of a number.
c-sum-digits.c
#include <stdio.h>
int main()
{
int num, r, s = 0;
printf("Enter a positive integer: ");
scanf("%d",&num);
while(num != 0)
{
r = num % 10;
s = s + r;
num = num / 10;
}
printf("\nThe sum of the digit is : %d ", s);
return 0;
}
Enter a positive integer: 756
The sum of the digit is : 18

Note:

Here we slice digits from last and summation the digits simultaneously. By looking at the program r = num % 10 slicing last digit from a variable num and storing it in a variable rs = s + r summation is done here and the result is stored in a variable s. num = num/10removing last digit completely from num variable.