C Program to find the sum of digits of the number entered.
C Program to find the sum of digits of the number with full explanation of the program.
#include<stdio.h>
#include<conio.h>
int sumdig(int n);
void main()
{ int n,s;
clrscr();
printf(“Enter the number:”);
scanf(“%d”,&n);
s=sumdig(n);
printf(“sum is %d”,s);
getch();
}
int sumdig(int n)
{ int r,sum=0;
while(n!=0)
{ r=n%10;
sum=sum+r;
n=n/10;
}
return sum;
}
Output :
Logic of the program
1. Let the number n is entered to be 45.
2. We have to seperate 4 &5 to add them individually.
3. For that firstly we will take the modulo of number with 10 i.e r=45 % 10=5
4. Value of sum is initially assigned to be 0, now the r is added to 0 and stored in sum. (sum=sum+r)
5. So now the value of sum gets 5.
6. Now the numer is divided by 10 i.e n=45/10=4;
7. So the value of n changes from 45 to 4.
8. And the loop will continue untill n is not equal to 0.
9. This logic can also be use for 3 digits number and more.
Moddulo operator(%)
It is an arithmetic operator.It divides one operand with another and produces the remainder of an integer division.
Ex-54 % 10= 4 (which is the remainder)
7 % 3=1
Division operator(/)
It is the arithmetic operator. It divides first operand by second operand and produces the result.
Ex-54/10=5(which is qu
7/3=2