Recursive function

Hello,

I would like to know how the output of this program is 12. I sort of get it, but not quite. Can someone please explain, mathematically, how this is so?

Thank you for taking the time to read.

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

int recursiveFunction(int x) {
    if(x < 5) return 4;
    return recursiveFunction(x / 4) + x % 6;
}

int main() {
    int e = 21;
    
    cout << recursiveFunction(e);        
}
Print inside the loop to give you an idea of what's going on step by step:
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;

int recursiveFunction(int x)
{
    cout << "Function called with x = " << x << '\n';
    if (x < 5)
    {
        cout << "x = " << x << "  Returning result: 4 (base case)\n";
        return 4;
    }
    else
    {
        int result = recursiveFunction(x / 4) + x % 6;
        cout << "x = " << x << "  Returning result: " << result << '\n';
        return result;
    }
}

int main()
{
    int e = 21;

    cout << recursiveFunction(e);
    return 0;
}
Function called with x = 21
Function called with x = 5
Function called with x = 1
x = 1  Returning result: 4 (base case)
x = 5  Returning result: 9
x = 21  Returning result: 12
12 
Last edited on
Topic archived. No new replies allowed.