Multiple functions problem

When i run it it says Program stopped working.

But i can't see what's the problem with the code. Does anyone know why is it giving an error ?


Here is the code:

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;

int f(int);
int h(int);
int g(int);

int g(int n)
{
    return g(0) == 0 ? 0 : (2 * f(n));
}
int f(int n)
{
    return f(0) == 0 ? 0 : (h(n) + g(n-1));
}
int h(int n)
{
    return h(0) == 0 ? 1 : (n *(h(n-1)));
}

int main()
{
    cout << f(3);
}


And this is the task i should solve with this code :

1
2
3
4
5
6
f(0) = 0
g(0) = 0
h(0) = 1
f(n) = h(n)+g(n-1)
g(n) = 2*f(n)
h(n) = n*h(n-1)
Last edited on
Looks like recursion which never terminates.
What's the first thing that happens after function f() is called?
Last edited on
Looks like recursion which never terminates.
What's the first thing that happens after function f() is called?


It does h(n) + g(n-1)
Last edited on
Not quite.

First of all it has to evaluate the condition (f(0) == 0) to determine whether it is true or false. As a result it calls function f() to find the value of f(0). Then it has to call f() again ...

If you have a debugger you can step through the code line by line, place a breakpoint in each function to see this.

Actually, I think the correct code might look like this,
1
2
3
4
int f(int n)
{
    return n == 0 ? 0 : (h(n) + g(n-1));
}
Oh okay, i see what you mean. The way i did it, it just does a endless loop. You are right ! Thanks so much for a quick response :)
Last edited on
Topic archived. No new replies allowed.