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)

I am having trouble with these types of functions. Any advice?
What have you written so far?
Right now im trying to figure out how to extract the digit before I even start doing the function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

int main(){
    
    int x;
    
    cout<<"blahblah";
    cin>>x;
    
    x=((x/10)%10);
    
    cout<<x;
    
    system("pause");
}
Let's say you have 5432 as the number.

5432/10 will chop off the 2, leaving you with 543.

5432%10 will keep only the 2.
i see.. im going to try that.. thanks for the explanation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

int main(){
    
    int number,n1,n2,n3,n4,result;
    
    cout<<"blahblah";
    cin>>number;
    
    n1=(number%10);
    number=number/10;
    n2=(number%10);
    number=number/10;
    n3=(number%10);
    number=number/10;
    n4=(number%10);
    number=number/10;
    
    result=n1+n2+n3+n4;
    cout<<result;
    
    system("pause");
}


I think im getting there.. just need to figure out how to make a recursive function.
There are two main considerations in writing recursive functions. The first is that it calls itself. This implies that the function does a finite portion of the work at hand. For example, in this case, it may process 1 digit and return the [accumulated] sum. The other consideration is that there must be an ending condition. Without this, the function would call itself infinitely (or until it runs out of stack space). In this case, when it runs out of digits to process, it is done.

Consider a recursive function to compute the factorial of a number, n. (Untested, of course.)
1
2
3
4
5
6
7
int factorial( int n ) {
    if( 1 == n ) {
        return 1; // ending condition
    }

    return factorial( n - 1 ) * n; // calls itself
}
Last edited on
this is what I have thus far? but results it isn't adding up for some reason

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
26
#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;
}
     
closed account (o1vk4iN6)
results is in the local scope of recur() so it doesn't exist outside of the function.

1
2
3
4
5
int recur(int number) // the number is returned
{
     if(number == 0) return 0;
     return recur(number / 10) + number % 10;
}
Topic archived. No new replies allowed.