facebook like button

15 July, 2011

Calculating sum of digits of a natural number

The need:
    This program was asked me by a reader of this blog.
The code:
-------------------------------------------------------

#include<stdio.h>
main()
{
    int number,i,sum=0;
    printf("enter a natural number.\n");
    scanf("%d",&number);
    if(number<1)
    {
        printf("the number entered was not a natural number.\n");
        exit(0);
    }
    i=number;
    while(i>0)
    {
        sum+=i%10;
        i=i/10;
    }
    printf("sum of digits of %d is %d\n",number,sum);
}

-------------------------------------------------------

No comments:

Post a Comment

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply