Sum Of Digits Program In C++ - C++ Programming Tutorial
C++ Course / C++ Programs / Sum Of Digits Program In C++

Sum Of Digits Program In C++

BLUF: Mastering Sum Of Digits Program In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Sum Of Digits Program In C++

C++ is renowned for its efficiency. Learn how Sum Of Digits Program In C++ enables low-level control and high-performance computing in the tutorial below.

We have the capability to develop a C++ program for calculating the sum of digits using loops and mathematical operations exclusively.

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++.

Example

Example

#include <iostream>

using namespace std;

int main()

{

int n,sum=0,m;  

cout<<"Enter a number: ";  

cin>>n;  

while(n>0)  

{  

m=n%10;  

sum=sum+m;  

n=n/10;  

}  

cout<<"Sum is= "<<sum<<endl;  

return 0;

}

Output:

Output

Enter a number: 23  

 Sum is= 5
Example

Enter a number: 624       

Sum is= 12

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience