C Programming

Sum of Digits of a Number

Sum of Digits of a number is taken out in two steps. One, using the modulus operator (%) and taking remainder by dividing by 10 to get individual digits and then diving the number itself by 10 to reduce the least significant. It is similar to reversing digits of the number.

Language : C

[sourcecode language='c']
//To find sum of digits of an entered number
#include
#include
void main()
{
int a,dig,s,last;
s=0;
printf(“Enter a number : “);
scanf(“%d”, &a);
last=a;

while(a!=0)
{
dig=a%10;
a=a/10;
s=s+dig;
}

printf(“\nThe sum of the digits of %d is : %d” , last , s);

getch();
}
[/sourcecode]



Leave a Comment

Notify me of followup comments via e-mail. You can also subscribe without commenting.


WordPress - Vaibhav Kanwal