CodesJava

Easy learning with example program codes

CPP program to print sum of digits


The below program gives the sum of all the digits in a variable using loop. The CPP cout object is used to output the result on the screen.

Logic:

Till the given Number is greater than 0.

Remainder = Modulus of Number with 10

Total Sum = Adding Remainder into the Total Sum

Number = Dividing Number by 10

Code:

#include <iostream.h>
using namespace std;
 
int main()  
{  
int x,y;
int sum = 0;
 
cout << "Enter a number to add digits: ";    
cin >> x;   
int num = x;
 
while(x>0)    
{    
y = x % 10;    
sum = sum + y;    
x = x / 10;    
}   
 
cout << "Sum of digits of " << num << " = " << sum;  
return 0;
}

Output

Enter a number to add digits: 4321   
Sum of digits of 4321 = 10
Posted in CPP   
Sign Up/ Sign In
Ask a Question


Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki