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<iostream>
using namespace std;
int main()
{
int n,i;
int sum=0,num=0;
int rem=0;
cout<<("ENTER THE NUMBER : \n");
cin>>n;
num=n;
while(num>0)
{
	rem=num%10;
	sum=sum+rem;
	num=num/10;
}	
cout<<"THE SUM OF DIGITS OF A NUMBER "<<n<<" IS : "<<sum;
return 0;
}

Output


ENTER THE NUMBER : 543452
THE SUM OF DIGITS OF A NUMBER : 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

Also see :


PROGRAM TO SWAP TWO NUMBERS USING XOR OPERATION

PROGRAM TO SWAP TWO NUMBERS USING THIRD VARIABLE

PROGRAM TO FIND THE REVERSE OF A NUMBER

PROGRAM TO CHECK WHETHER A GIVEN NUMBER IS PALINDROME OR NOT

PROGRAM TO GENERATE THE FACTORIAL OF A NUMBER

PROGRAM TO EVALUATE THE SUM OF FIRST 'N' NUMBERS

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

Join us :



CODE OF GEEKS

A Platform to LEARN | CODE | ACHIEVE

Connect :



INTERESTING READ FOR YOU :

TOP PROGRAMMING LANGUAGES THAT ARE RULING IN 2018.
TOP PROGRAMMING LANGUAGES FOR WEB DEVELOPMENT IN 2018.
TOP PROGRAMMING LANGUAGE FOR A.I. & MACHINE LEARNING

SHARE:



For any Queries,suggestions,feel free to Mail us at :
[email protected]

For reporting any kind of copyright voilation,mail us at : [email protected]

© copyright CODE OF GEEKS 2018

ALL RIGHTS RESERVED