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.
1 2 3 4 5 6 | 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 https://www.youtube.com/watch?v=UnXfCTtHNWw]
Full Free Source code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include < stdio.h > #include < conio.h > 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
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.
In the while loop, I think it must be like this ‘ while(num>0) ‘
while( num > 0 ) is also right and writing just while( num ) is also correct.
Try them out..it means one and the same.