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

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?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics