Sunday, September 11, 2011

find the sum of digits of any given integer

/* to find the sum of digits of  any given integer */
#include<stdio.h>
#include<conio.h>
main()
{
//declare int variable n for number for which have to find addition
//m is for temp variable to store rest value
//x is for the single digit/reminder from whole number
//sum which is initialized as 0 to store a sum of the number
    int n,m,x,sum=0;
//clears the screen
    clrscr();
//print msg to screen to enter a number
    printf("\ngive the number:");
//read input from user and store it to n
    scanf("%d",&n);
//store entered number to temp variable m
    m=n;
// start while number number is greater then 0
  while(n>0)
    {
//divide the number by 10 and store the reminder in x
    x=n%10;
//add x to sum
    sum=sum+x;
//again divide n by 10 and store it to n
    n=n/10;
//again check n>0 if yes go to top else exit while
}
//print the given/inputed digit
    printf("\ngiven number is =%d",m);
//print the sum of digit
    printf("\nsum of digits of given number is =%d",sum);
//wait for response
       getch();
       }

No comments:

Post a Comment

Popular 5 Posts Last 7 days