Monday, 8 December 2014

C program to find sum of digits of a number

program to find sum of digits of a number
#include<stdio.h>
#include<stdlib.h>
main()
{
int n,sum=0,rem,k;
printf("enter value for n\n");
scanf("%d",&n);
k=n;
for(;n>0;n=n/10)
{
rem=n%10;
sum=sum+rem;
}
printf("sum of digits of %d is %d\n",k,sum);
}
OutPut:
madan@madan-Lenovo-G570:~/madan$ cc ex49.c
madan@madan-Lenovo-G570:~/madan$ ./a.out
enter value for n
5
sum of digits of 5 is 5
madan@madan-Lenovo-G570:~/madan$ ./a.out
enter value for n
12345
sum of digits of 12345 is 15