The ones who are crazy enough to think they can change the world are the ones who do.
- Steve Jobs

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 r. s = s + r summation is done here and the result is stored in a variable s. num = num/10 removing last digit completely from num variable.

Report Us

We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.

Report