Calculate Sum of Digits: C Program


Lets ask the user to input a integer number through keyboard. Lets write a c program to calculate sum of its digits.

Related Read:
Find Sum of Digits In A Given Number: C

Note: We assign variable sum = 0 to avoid garbage values in sum.

If user enters 456, we apply the modulo division to get the individual values.
Ex:
456 % 10 = 6
45 % 10 = 5
4 % 10 = 4

We get 456, 45 and 4 by dividing the original value by 10.
Ex:
456 user entered value.
456 / 10 = 45
45 / 10 = 4

Now the sum.

sum = sum + rem;

06 = 0 + 6
11 = 6 + 5
15 = 11 + 4

So the sum of digits in the given integer number is 15.

Calculate Sum of Digits: C Program


[youtube https://www.youtube.com/watch?v=CdHLY5S2Xdc]

YouTube Link: https://www.youtube.com/watch?v=CdHLY5S2Xdc [Watch the Video In Full Screen.]


Source Code: Calculate Sum of Digits: C Program

#include < stdio.h >

int main()
{
    int num, reminder, sum = 0;

    printf("Enter a integer number\n");
    scanf("%d", &num);

    while(num != 0)
    {
     reminder = num % 10;
     sum      = sum + reminder;
     num      = num / 10;
    }

    printf("Sum of digit is %d\n", sum);

    return 0;
}

Output 1:
Enter a integer number
456
Sum of digit is 15

Output 2:
Enter a integer number
8910
Sum of digit is 18

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Leave a Reply

Your email address will not be published. Required fields are marked *