Problem
Statement
In
this program we will code a basic program to evaluate the sum of digits in C
programming language.
Code
#include
int sumofdigits(int n)
{
int sum=0,num=0;
int rem=0;
num=n;
while(num>0)
{
rem=num%10;
sum=sum+rem;
num=num/10;
}
return sum;
}
int main()
{
int n;
printf("Enter
the number ?\n");
scanf("%d",&n);
int
res=sumofdigits(n);
printf("Sum of
digits : %d",res);
return 0;
}
Output
Enter
the number ? – 12345
Sum
of digits : 15
Explanation
In
this problem we have to find the sum of digits of a ‘n’th number.To do so we
declare a variable ‘sum’,which will store the result value (don’t forget to
initialize it with zero).
Let
us consider an example :
Let the number be 23417 so our task is to evaluate 2+3+4+1+7. We can do so by
finding the remainder of a number(adding it to sum),divide it with 10 until the
number gets 0. For this we need a ‘while’ loop which will run till ‘N>0’.In
each iteraion we perform three steps :
1. rem=num%10;
//rem=23417%10=7
2. sum=sum+rem; //sum=7
3. num=num/10;
//num=23417/10=2341
Hence
on repeating these steps(till n>0), we get the sum of digits of a number.


0 Comments