we determined the sum of digits of a non-negative integer number by determining the least significant digit and then removing it from given number.
In this example, we generalize this technique to determine the sum of digits of any non-negative integer number. To separate the digits of given number num, we can use a while loop as shown below:
while (num > 0)
digit = num % 10;
num /= 10;
In each iteration of this loop, the least significant digit of number num is separated in variable digit and then removed from the given number. The statements within this loop are executed as long as the value of num is greater than zero, i. e., as long as the number contains one or more digits.
Note that the value of digit will be modified in subsequent iterations. Thus, we should immediately add it to variable sum used to store the sum of digits. The variable sum should be initialized to zero before the loop. The program segment given below determines the sum of digits of the number num: ·
sum = 0;
while (num > 0)
digit = num % 10;
sum += digit;
num /= 10;
Note that this program works correctly even if the given number is zero. The complete program given below accepts a number from the keyboard, determines the sum of its digits and prints the sum.
#include <stdio.h>
void main()
{
int num,digit,sum;
clrscr();
printf(“Enter positive numbers:\n”);
scanf(“%d”,&num);
sum=0;
while (num > 0)
{
digit = num % 10;
sum += digit;
num /= 10;
}
printf (“Sum Digit = %d “, sum);
getch();
}