The program segment given below determines the sum of digits of a given number repeatedly until a single digit number is obtained. For example, 5985 => 27 => 9, where symbol => indicates a digit sum operation. Thus, if digit sum exceeds 9, it is used as a number for subsequent digit sum operations.
This code uses a two-level nested do … while loop. The inner do … while loop is used to determine the sum of digits of number num. After the sum of digits is calculated in the inner do … while loop, it is assigned to num as a new number. The outer do … while loop determines the sum of digits repeatedly as long as num is greater than 9.
#include <stdio.h>
void main()
{
int num,sum;
clrscr();
printf(“Enter a Number :”);
scanf(“%d”,&num);
do
{
sum = 0; /* sum of digits of number */
do
{
sum += num % 10; /* add LS digit to sum */
num /= 10; /* remove LS digit from num */
} while (num > 0);
num = sum; /* use digit sum as new number */
} while (num > 9); /* as long as num has 2 or more digits */
printf(“Sum of digits %d\n”, sum);
getch();
}