Home » Programming » C++ » Program of Sum of digits in C++

Program of Sum of digits in C++

This article shows that Program of Sum of digits in C++. We can write the sum of digits of number program in C++ language by the help of loop and mathematical operation only.

Sum of digits algorithm

To get sum of each digit of number by C++ program, use the following algorithm:

  • Step 1: Get number by user
  • Step 2: Get the modulus/remainder of the number
  • Step 3: sum the remainder of the number
  • Step 4: Divide the number by 10
  • Step 5: Repeat the step 2 while number is greater than 0.

Reverse Number Program in C++.

Let’s see the sum of digits program in C++.

#include <iostream>  
using namespace std;  
int main()  
{  
int n,cn,sum=0,rem;    
cout<<"Enter a number: ";    
cin>>n;    
cn = n; 
while(n>0)    
{    
rem=n%10;    
sum=sum+rem;    
n=n/10;    
}    
cout<<"Sum of digits of number "<< cn << " = "<<sum<<endl;    
return 0;  
}  

Output:

Enter a Number: 66
Sum of digits of number 66 = 12
Enter a Number: 666
Sum of digits of number 666 = 18
Note: If you interested lo learn C++ through web, You can click here

Conclusion:

Hi guys, I can hope that you can know that how to write a Program of Sum of digits in C++. If you like this post as well as know something new so share this article in your social media accounts. If you have any doubt related to this post then you ask in comment section.

Leave a Reply

Your email address will not be published. Required fields are marked *