SHARE

Get a number, add all the digits and print the sum.

Explanation:

First take a number and store it in variable ‘n’. Now we want each and every digit to be added. Let’s take an example:

My variable n is 1234

1234/10=123; remainder:4 ;

123/10=12; remainder:3 ;

12/10=1; remainder:2 ;

1/10=0; remainder:1 ;

In above logic you can see remainder has all the digits of the number. So, When we add all the digits of remainder, we will get the sum of the digits.

I take variable r to store the remainder, sum to store addition of remainder.

First: r = n%10;   //1234%10=4

Second: n= n/10; // 1234/10= 123

Third: sum=sum +r; //0+4=4

Now put this three in a loop such that n should always be greater than 0. If n is 0 then it will exclude from the loop.

code:

#include <stdio.h>
#include <conio.h>

void main()
{
int n,r, sum=0;
printf(“\n Enter The Number:”);
scanf(“%d”,&n);

while(n>0)
{
r=n%10;
n=n/10;
sum=sum+r;
}

printf(“\n Sum Of Digits is: %d”,sum);

getch();
}

Output:

Enter The Number:2443546

Sum Of Digits is: 28

LEAVE A REPLY

Please enter your comment!
Please enter your name here