### Recursive digit addition

Write a recursive function that does the following:

Given a number, add all the digits and display the sum.
Example:
The sum of the number 5432 would be 14.
 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657`` `````` #include using namespace std; int add (int input, int sum, int temp, int temp2) { if (input > 1000 ) { temp = 1000; } else if (input > 100) { temp = 100; } else if (input > 10) { temp = 10; } else if (input > 0) { temp = 1; } sum = input/temp; temp2 += sum; input = input - (sum * temp); add(input, sum, temp, temp2); cout << temp2; } int main() { int input = 0; int sum = 0; int temp = 0; int temp2 = 0; int counter = 4; cout << "Please input number." << endl; cin >> input; add(input, sum, temp, temp2); }``````

Every time I run this program recursively it crashes. But if I use a while loop, it works fine. Any help?
Never mind. I got it.
 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061`` ``````#include using namespace std; int add (int input, int sum, int temp, int temp2) { if (input > 1000 ) { temp = 1000; } else if (input > 100) { temp = 100; } else if (input > 10) { temp = 10; } else if (input > 0) { temp = 1; } else { cout << temp2; return 0; } sum = input/temp; temp2 += sum; input = input - (sum * temp); add(input, sum, temp, temp2); } int main() { int input = 0; int sum = 0; int temp = 0; int temp2 = 0; int counter = 4; cout << "Please input number." << endl; cin >> input; add(input, sum, temp, temp2); }``````
 ``123456789101112131415`` ``````#include using namespace std; int sumDigits( int n ) { if ( n < 10 ) return n; else return sumDigits( n / 10 ) + n % 10; } int main() { int n; cout << "Input a positive number: "; cin >> n; cout << "Sum of digits is " << sumDigits( n ); }``````

 ```Input a positive number: 1234567 Sum of digits is 28```
Topic archived. No new replies allowed.