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++ program 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;

// Function to find the sum of digits of a number until a single digit is obtained
int addDigits(int num) {
    // Formula to get the sum of digits until a single digit is achieved
    return num - (num - 1) / 9 * 9;
}

int main(void) {
    // Test cases to find the single digit sum of numbers
    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; // Return 0 to indicate successful completion
}

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?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/cpp-exercises/math/cpp-math-exercise-11.php