//Program
to Add digits of a number
#include <stdio.h>
#include <conio.h>
void main()
{
int n, sum = 0, rem;//Initialize the value of sum as zero
clrscr();
printf("Enter an integer\n");
scanf("%d",&n);
while(n != 0)//while n is not equal to zero
{
rem = n % 10; //it gives us the remainder
sum = sum + rem;
n = n / 10; //it gives us the quotient
}
printf("Sum of digits of entered number
= %d\n",sum);
getch();
}Explanation:-
Let the entered number is n = 347
Step 1:
n = 347 is not equal to zero
rem = 347 % 10 = 7
sum = 0 + 7 = 7
n = 347/10 = 34
Step 2:
n = 34 is not equal to zero
rem = 34 % 10 = 4
sum = 7 + 4 = 11
n = 34/10 = 3
Step 3:
n = 3 is not equal to zero
rem = 3 % 10 = 3
sum = 11 + 3 = 14
n = 3/10 = 0
Step 4:
n = 0 is equal to zero
Termination of loop
Now printing of sum of digits will be there i.e. sum=14
No comments:
Post a Comment
Note: only a member of this blog may post a comment.