A program to determine the sum of digits of a given non-negative integer number using a while loop is presented in Program. The program segment given below does the same thing using a do…while loop.
sum = 0; do { sum += num % 10; /* add LS digit to digit sum */ num /= 10; /* remove LS digit from num */ while (num > 0); }
The only problem with this implementation is that the statements within the loop will be executed at least once giving incorrect results for negative numbers. To ensure that the given number num is non-negative, we can declare it of type unsigned int.
Example:
#include<stdio.h> void main() { int num,sum; /* given numbers */ clrscr(); printf("Enter integer numbers: "); scanf ("%d", &num); sum = 0; do { sum += num % 10; /* add LS digit to digit sum */ num /= 10; /* remove LS digit from num */ } while (num > 0); printf ("The Sum is = %d \n",sum); getch(); }