Header Ads Widget

Ticker

6/recent/ticker-posts

Sum of digits program in C++ Notes+Coding by Digitalise Data

Sum of digits program in C++ Notes+Coding by Digitalise Data

Sum of digits program in C++

We can write the sum of digits program in C++ language by the help of loop and mathematical operation only.

Sum of digits algorithm

To get sum of each digit 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.

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

  1. #include <iostream.h>
  2. #include <conio.h>   
  3. void main()  
  4. {  
  5. int n,sum=0,m;    
  6. cout<<"Enter a number: ";    
  7. cin>>n;    
  8. while(n>0)    
  9. {    
  10. m=n%10;    
  11. sum=sum+m;    
  12. n=n/10;    
  13. }    
  14. cout<<"Sum is= "<<sum<<endl;    
  15. getch();  
  16. }  

Output

Enter a number: 23  
 Sum is= 5

Enter a number: 624        
Sum is= 12 

Post a Comment

0 Comments