- #1
- 4,652
- 38
Hi,
I am playing around with doing stuff recursively, just to practice, and I have a problem I can't work out. I want to write a recursive function that will sum the digits of a number, take the result, sum those digits, etc. until I reach a single digit number. Then I want to return that single digit number from my function.
In other words, if I start with number 4322:
4322 => 4+3+2+2 = 11,
11 => 1+1 = 2
so 2 is the number I want to return
What I've been able to do so far is write a little program that goes through one iteration of summing the digits. I know that when I make the function I'll need to pass the sum back to the function, and I think my stopping condition will be when the number passed in is a single digit, but I'm still not sure how to set this all up. Any help is appreciated. Thanks.
I am playing around with doing stuff recursively, just to practice, and I have a problem I can't work out. I want to write a recursive function that will sum the digits of a number, take the result, sum those digits, etc. until I reach a single digit number. Then I want to return that single digit number from my function.
In other words, if I start with number 4322:
4322 => 4+3+2+2 = 11,
11 => 1+1 = 2
so 2 is the number I want to return
What I've been able to do so far is write a little program that goes through one iteration of summing the digits. I know that when I make the function I'll need to pass the sum back to the function, and I think my stopping condition will be when the number passed in is a single digit, but I'm still not sure how to set this all up. Any help is appreciated. Thanks.
Code:
# include <iostream>
using namespace std;
int main()
{
int n = 4322;
int sum = 0;
while (n > 0)
{
sum = sum + n%10;
n = n/10;
}
cout << sum <<endl;
return 0;
}