C++ program to find sum of digits of a number

Advertisements

Prev Tutorial Next Tutorial

C++ program to find sum of digits of a number

Sum of digits means add all the digits of any number, for example we take any number like 358. Its sum of all digit is 3+5+8=16. Using given code we can easily write c++ program.

C++ program to find sum of digits of a number


#include<iostream.h>
#include<conio.h>
void main()
{
int a,no,sum=0;
clrscr();
cout<<"Enter any num : ";
cin>>no;
while(no>0)
{
a=no%10;
no=no/10;
sum=sum+a;
}
cout<<"\nSum of digits: "<<sum;
getch();
}

Output

Enter any number : 584
Sum of digits : 17

Explanation of code

a=no%10;

Here we find remainder of given number, using Modulo Operator we find remainder of any number, Using this step we get only last digits.

a=no/10;

Here After dividing any number by 10 we get all digits except last digits.

Sum=Sum+a;

Using this statement we find sum of all digits. In first iteration it add 0 and last digits and store in Sum variable, in second iteration it add Previous sum values and last digits of new number and again store in Sum variable, and so on upto while condition is not false.


Prev Tutorial Next Tutorial

Google Advertisment

Buy This Ad Space @$20 per Month, Ad Size 600X200 Contact on: hitesh.xc@gmail.com or 9999595223

Magenet is best Adsense Alternative here we earn $2 for single link, Here we get links ads. Magenet

For Projects 9999595223

Google Advertisements


Buy Websites 9999595223

Buy College Projects with Documentation Contact on whatsapp 9999595223. Contact on: hitesh.xc@gmail.com or 9999595223 Try this Keyword C++ Programs

Advertisements