We will write the sum of digits program in C++. Before that, you should have knowledge of the topics in C++ given below.
The program takes a user input for the integer whose sum of the digits needs to be found. Then using while loop, we will iterate the number and extract each digits and add it to the following one.
Lastly, we will display the sum of digits of that number. Let us go through the program.
C++ Program to Find Sum of Digits of a Number
In this program, we will use a while loop to iterate through the number. You can also do that using for loop.
C++ program to display the sum of the digits using a while loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include <iostream> using namespace std; int main() { int num, rem, sum = 0; cout << "Enter the Number: "; cin >> num; while (num > 0) { rem = num % 10; sum += rem; num /= 10; } cout << "Sum of Digits: " << sum; return 0; } |
Output:
Enter the Number: 123
Sum of Digits: 6
C++ Program to Calculate the Sum of Digits of a Number using for loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include <iostream> using namespace std; int main() { int number, rem, sum = 0; cout << "Enter the Number: "; cin >> number; for (sum = 0; number > 0; number /= 10) { rem = number % 10; sum += rem; } cout << "Sum of Digits: " << sum; return 0; } |
Output: After successful execution of the above program, it will create the same output as the above one.