Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C++ Exercises: Find the sum of digits of a given number

C++ For Loop: Exercise-10 with Solution

Write a program in C++ to find the sum of digits of a given number.

Pictorial Presentation:

C++ Exercises: Find the sum of digits of a given number

Sample Solution :-

C++ Code :

#include <iostream>
using namespace std;
int main()
{
    int num1, num2, r, sum=0;
    cout << "\n\n Find the sum of digits of a given number:\n";
    cout << "----------------------------------------------\n";
    cout << " Input a number: ";
    cin >> num1;
    num2 = num1;
    while (num1 > 0) 
    {
        r = num1 % 10;
        num1 = num1 / 10;
        sum = sum + r;
    }
    cout << " The sum of digits of " << num2 << " is: " << sum << endl;
}

Sample Output:

 Find the sum of digits of a given number:                             
----------------------------------------------                         
 Input a number: 1234                                                  
 The sum of digits of 1234 is: 10  

Flowchart:

Flowchart: Find the Greatest Common Divisor (GCD) of two numbers

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a program in C++ to find the Greatest Common Divisor (GCD) of two numbers.
Next: Write a program in C++ to find the sum of the series 1 + 1/2^2 + 1/3^3 + …..+ 1/n^n.

What is the difficulty level of this exercise?