Electrofriends

To find the sum of digits

by Ranjith | December 4th, 2008.

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(“\n\n\t ENTER A NUMBER…: “);
scanf(“%ld”,&num);
while(num>0)
{
dig = num % 10;
sum = sum + dig;
num = num / 10;
}
printf(“\n\t SUM OF DIGITS IS…: %ld”, sum);
getch();
}

Download exe and source code here.


Share and Enjoy:
  • Digg
  • Technorati
  • StumbleUpon
  • Twitter
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Reddit
  • Mixx
  • Yahoo! Buzz
  • LinkedIn
  • NewsVine
  • RSS
  • email
Similar Posts:

Leave a Reply

Share and enjoy

    • Digg
    • Facebook
    • Technorati
    • StumbleUpon
    • Twitter
    • Reddit
    • del.icio.us
    • Yahoo! Buzz
Copyright©2009 www.electrofriends.com All Rights Reserved. Powered by Dhyeya