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: Add repeatedly all digits of a given non-negative number until the result has only one digit

C++ Math: Exercise-11 with Solution

Write a C++ programming to add repeatedly all digits of a given non-negative number until the result has only one digit.

Input: 58
Output: 4
Explanation: The formula is like: 5 + 8 = 13, 1 + 3 = 4.

Sample Solution:

C++ Code :

#include <iostream>
using namespace std;

int addDigits(int num) {
        return num - (num - 1) / 9 * 9;
    }

int main(void)
{
    int n = 15;
    cout << "\nInitial number is "<< n << " single digit number is " << addDigits(n) << endl; 
    n = 57;
    cout << "\nInitial number is "<< n << " single digit number is " << addDigits(n) << endl; 
    return 0;   
}

Sample Output:

Initial number is 15 single digit number is 6

Initial number is 57 single digit number is 3

Flowchart:

Flowchart: Add repeatedly all digits of a given non-negative number until the result has only one digit.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to count the total number of digit 1 appearing in all positive integers less than or equal to a given integer n.
Next: Write a C++ programming to check if a given integer is a power of three or not.

What is the difficulty level of this exercise?