Help with recursive function!!

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.



Hint (Divide and mod by 10 to extract each digit)



This is what I have so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
using namespace std;

void recur(int);

int main(){
    
    int number,digit,results;
    
    cout<<"blahblah ";
    cin>>number;
    recur(number);
    system("pause");
}

void recur(int number){
     int results, digit;
     
     if (number!=0){
        digit=number%10;
        results=results+digit;
        recur(number/10);
     }
     cout<<results;
}


Last edited on
Don't put a cout in a recursive function. You can't control how many prints you'll get. But perhaps that is for debugging.

Results is never initialized.

Return an int, this lets the calling functions use the value itself.

Something like this might be what you are looking for:
1
2
3
4
5
6
7
8
9
10
11
12
int recur(int number) {
    if (number <10) {
        return number;
    }
    else {
        int digit = number%10;
        int remainder = number / 10; // This represents the other digits

        int results = digit + recur(remainder);
        return results;
    }
}


That can be simplified to:
1
2
3
4
int recur(int number) {
    if (number < 10) return number;
    return number%10 + recur(number/10);
}


You would use it like this:
1
2
3
4
5
6
int main() {
    int number;
    cout << "blahblah ";
    cin >> number;
    cout << recur(number);
}
Last edited on
Topic archived. No new replies allowed.