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 Link: https://www.youtube.com/watch?v=CdHLY5S2Xdc [Watch the Video In Full Screen.]


Source Code: Calculate Sum of Digits: C Program

  1. #include < stdio.h >  
  2.   
  3. int main()  
  4. {  
  5.     int num, reminder, sum = 0;  
  6.   
  7.     printf("Enter a integer number\n");  
  8.     scanf("%d", &num);  
  9.   
  10.     while(num != 0)  
  11.     {  
  12.      reminder = num % 10;  
  13.      sum      = sum + reminder;  
  14.      num      = num / 10;  
  15.     }  
  16.   
  17.     printf("Sum of digit is %d\n", sum);  
  18.   
  19.     return 0;  
  20. }  

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 *