#### CODE OF GEEKS

A PLATFORM TO LEARN | CODE | ACHIEVE

" Programming is the real test of your creativity,its all about how you turn ideas into codes. "

Connect :

THIS WEBSITE IS BEST VIEWED IN THE GOOGLE CHROME WEB BROWSER.

#### TO GENERATE THE SUM OF ALL DIGITS OF A NUMBER IN C

Code

```#include<stdio.h>
int main()
{
int n,i;
int sum=0,num=0;
int rem=0;
printf("ENTER THE NUMBER : \n");
scanf("%d",&n);
num=n;
while(num>0)
{
rem=num%10;
sum=sum+rem;
num=num/10;
}
printf("THE SUM OF DIGITS OF A NUMBER %d IS : %d\n",n,sum);
return 0;
}
```

Output

ENTER THE NUMBER : 543452
THE SUM OF DIGITS OF A NUMBER 543452 IS : 23

What we did - Our Approach

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.

See this code in :

C++

Java

Participate in our MONTHLY CHALLENGE,and get a chance to get listed on our site and win the TITLE of "MR.GEEK".

RUSH TO OUR MONTHLY CHALLENGE

#### A Platform to LEARN | CODE | ACHIEVE

Connect : 