so the question is:
**cant use loops in the recursive functions, only for input check
Write a program that uses a recursive function (or function) that receives a positive integer from the user and calculates the "final amount" of his digits.
The sum of the final digits of a number is the result of a process in which calculates the sum of digits of the number and if the sum is not a single digit number and return the sum the digits of the sum until you get a single digit number.
example :
The sum of the digits of 96437 is 29 9 + 6 + 4 + 3 + 7 = 29 And the sum of the digits of 29 is 11 2 + 9 = 11 And the sum of the digits of 11 is 2 1 + 1 = 2
I figured how to use recursion to calculate sum of a number but dont know how to put the right condition to do it so it will be single digit number.
Student for bioinformatics, tried to use if condition in main but cant think of something good.
#include <iostream>
using namespace std;
// recursive function to find sum of digits of a number
int sum(int x)
{
if (x == 0)
{
return 1;
}
return (x % 10 + sum(x / 10));
}
int main()
{
int n, result;
// input and input check for positive number
do{
cout << "Please enter a positive number:"<< endl;
cin >> n;
cout << endl;
} while (n <= 0);
result = sum(n);
if (result % 10 == 0)
{
cout << result << endl;
}
else
{
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…