Find Sum of Digits In A Given Number: C

Video Tutorial to illustrate, C Program to find sum of digits in the given/user entered integer number.

In this program we assign variable sum = 0 to avoid garbage values in sum before the calculation, which would result in wrong output.
We store the user entered value in num.

 while( num )
  {
    rem = num % 10;
    sum = sum + rem;
    num = num / 10;
  }

Here the loop executes until the value of num is zero.

If user enters 123, we apply the modulus to get the individual values.
Ex:
123 % 10 = 3
12 % 10 = 2
1 % 10 = 1

We get 123, 12 and 1 by dividing the original value by 10.
Ex:
123 user entered value.
123 / 10 = 12
12 / 10 = 1

Now the sum.

sum = sum + rem;

3 = 0 + 3
5 = 3 + 2
6 = 5 + 1

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

Video Tutorial: Find Sum of Digits In A Given Number: C



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



Full Free Source code

#include 
#include 

void main()
{
 int num, rem, sum = 0;
 clrscr();

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

 while(num)
 {
   rem = num % 10;
   sum = sum + rem;
   num = num / 10;
 }

 printf("\nThe sum of digits is %d", sum);
 getch();
}

Output:
Enter an integer number
123
The sum of digits is 6



View Comments

  • The while loop keeps repeating for how many times? There is no condition for while loop then how does it work?

    • @shubh, num is divided by 10 each time the control enters the loop.
      So once the variable num becomes zero the condition becomes false and it no more enters the loop.

    • while( num > 0 ) is also right and writing just while( num ) is also correct.
      Try them out..it means one and the same.