C Program to find the sum of digits of a number

The following C program finds the sum of digits of a number.

Expected Output:

Run 1:

Run 2:

How it works

The following table demonstrates the algorithm we used to find the sum of digits of the a given number:

Iteration remainder sum  n
After 1st iteration remainder = 12345%10 = 5   sum = 0+5 = 5 n = 12345/10 = 1234
After 2nd iteration remainder = 1234%10 = 4   sum = 5+4 = 9 n = 1234/10 = 123
After 3rd iteration remainder = 123%10 = 3   sum = 9+3 = 12 n = 123/10 = 12
After 4th iteration remainder = 12%10 = 2   sum = 12+2 = 14 n = 12/10 = 1
After 5th iteration remainder = 1%10 = 1   sum = 14+1 = 15 n = 1/10 = 0

Recommended Reading:

Leave a Comment

%d bloggers like this: