Here is the program to find the sum of the digits of the entered number. Main idea in this program is to slice down the given number into digits and to operate on them.
Logic : The program asks the user to enter the number, to find out the sum of its digits. Sets the flag ‘sum’ to zero, implies that sum till now is Nil. Stores the entered number as Num. The while loop slices the number into digits. In each iteration, the current digit gets added up to the flag ‘Sum’ . Finally it prints out the number.
The same logic can be implemented for other programs too, where the situation comes to slice up the given number, as in the case of Reversing the number.
long int num,sum = 0,dig;
printf(“\n\n\t ENTER A NUMBER…: “);
dig = num % 10;
sum = sum + dig;
num = num / 10;
printf(“\n\t SUM OF DIGITS IS…: %ld”, sum);
Leave a Reply