Search Your Query

Custom Search

Monday 30 May 2011

To find the sum of digits


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.
#include<stdio.h>
#include<math.h>
void main()
{
long int num,sum = 0,dig;
clrscr();
printf(“nnt ENTER A NUMBER…: “);
scanf(“%ld”,&num);
while(num>0)
{
dig = num % 10;
sum = sum + dig;
num = num / 10;
}
printf(“nt SUM OF DIGITS IS…: %ld”, sum);
getch();
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...