Q:

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

0

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 Output:

Initial number is 15 single digit number is 6

Initial number is 57 single digit number is 3

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#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;   
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now