How to write a program that find the sum of all digits in a number?
In this tutorial we will learn how to write a program that find and display the sum of all digits in a number.
In this tutorial we will learn how to write a program that find and display the sum of all digits in a number.
Explanation:-
Here we did initialization for
dum----->To store the entered value(i.e 'n') as you will come to know at the end of the program.
n----------->To store number given by user.
sum----->To store the sum of all digits in the number.It is initialized to zero.
x---------->To store n%10.
First of all we got a number 'n' from user and then stored it in a dummy variable called as 'dum' for restoring the value.(remember this point).
Now the main logic comes here:-
let the number 'n' be 321 and as 321>0,while loop gets executed
then x=321%10--->which is 1.
sum=0+1-------->1
n=321/10--------->32
The sum for the first loop execution is sum=1.
Now the number 'n' has become '32' and n>0,while loop executes for 2nd time
then x=32%10--->which is 2.
sum=1+2-------->3
n=32/10--------->3
The sum when loop executed second time is sum=3.
Now the number 'n' has become '3' and n>0,while loop executes for 3rd time
then x=3%10--->which is 3.
sum=3+3-------->6
n=3/10--------->0
The sum when loop executed third time is sum=6.
Now as the number in variable 'n' is 0 which is not n>0 then the loop terminates.Then the final sum is '6'.
So now I hope you understood why the dummy variable is used.It is because the value in 'n' becomes 0 at the end of the program so for restoring this value to print at the end we used 'dum'(as from the 2nd point).
Finally it prints the value in 'sum'.
C program code
#include<stdio.h>
#include<conio.h>
void main()
{
int dum,n,sum=0,x;
printf("\n Enter a number:\n ");
scanf("%d",&n);
dum=n;
while(n>0)
{
x=n%10;
sum=sum+x;
n=n/10;
}
printf("\n The sum of all digits in %d is %d\n",dum,sum);
getch();
}
OUTPUT 1:
OUTPUT 2:
In first output,the input value is 7869
The sum of all digits in this number is 30
7 + 8 + 6 + 9 = 30
As the same in second output, the input value is 5562
The sum of all digits in this number is 18
5 + 5 + 6 + 2 = 18
Please share this post and blog link with your friends.For more programs use this blog.
If you have any problem, please comment in comment box, subscribe this blog for notifications of new post on your email and follow this blog.
Created by-- HARSH CHAUHAN
No comments:
Post a Comment