Here’s a C Program to find the sum of digits of an integer with output and proper explanation. The program uses while loop.
# include <stdio.h> # include <conio.h> void main() { int n, r, s = 0 ; clrscr() ; printf("Enter a number: ") ; scanf("%d", &n) ; while(n > 0) { r = n % 10 ; s = s + r ; n = n / 10 ; } printf("\nThe sum of the digits is: %d", s) ; getch() ; }
Output of above program
Enter a number: 1234
The sum of the digits is: 10
Explanation of above program
In this program we are first inputting an integer, counting the sum of digits of that number and finally displaying the output to the user. Let’s see how the above program does this.
There are three variables -
- n - An integer to store the number.
- s - An integer to store the sum of digits of n. s is initialized to 0.
- r - An integer that stores the remainder (we will get to that in a minute)
Now we are asking the user to enter a number and storing it in the
variable n. After that our while loop calculates the sum of digits of n.
To understand what is happening in while loop it’s better to take an
example. Suppose, user entered 1234. The process of while loop with n =
1234 is as follows -
Facts: Whenever you take modulus of a number with 10 i.e. modulo 10, it always returns the last digit of that number.
- First n > 0 i.e. 1234 > 0, so the program will enter in the while loop.
- In the next step, n % 10 is calculated and stored in r i.e. r = 1234 % 10 = 4 (last digit of n).
- Now the above value of r is added to the variable s. After this step, s = 4.
- Now the number (n) is divided by 10 and result is stored again in n i.e. n = n / 10 or n = 1234 / 10. Now as you know when you divide two numbers and store the result in an integer variable, only integer part of that result is stored in that integer variable not the fractional part. So when you divide 1234 by 10, even when the correct result is 123.4 the new value of n will be 123 i.e. after this step n = 123 and s = 4.
- Now that all statements inside the while loop has been executed once, the looping condition is again checked.
- Again n > 0 i.e. 123 > 0, so the program will again enter the while loop and above steps are followed in the same manner.
- Again, n % 10 is calculated and stored in r i.e. r = 123 % 10 = 3 (last digit of n).
- Now the above value of r is again added to the variable s. After this step, s = 7.
- Now the number (n) is divided by 10 and result is stored again in n i.e. n = n / 10 or n = 123 / 10. So after this step n = 12 and s = 7.
- Again n > 0, so the while loop will again execute following the above process.
- Once the value of n becomes 0 or less than 0, the while loop will exit and rest of the program will continue execution.
Tip: To understand the program you can also take different values of n and try the above process yourself. It will help you to understand the process much clearly and helps in improving your debugging ability.
really so much helpful :)
this is so nice..the best and the simplest