Problem with Ackermann-Funktion

Hey guys, my program is stuck in the endless loop, and i can't seem to find a problem. It works for A(1,2) but for (4,3) it gives endless loop.

Here's 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
26
27
28
29
30
31
#include <iostream>

using namespace std;

int A(int n, int m)
{
    if(n == 0)
    {
        return (m + 1);
    }
    else if(m ==0 && n>0)
    {
        return (A(n-1,1));
    }
    else if(n>0 && m>0)
    {
        return(A(n-1, A(n, m-1)));
    }
}

int main()
{
    int n, m = 0;
    cout << "Enter n and m : " << endl;
    cin >> n;
    cin >> m;

    cout << A(n,m);

    return 0;
}


Here is the task i need to do :
1
2
3
A(0,m)=m+1
A(n,0)=A(n-1,1) falls n>0
A(n,m)=A(n-1,A(n,m-1)) falls n>0 und m>0
Last edited on
One problem I see is this:

In your function. You have if statements. But what if non of the 3 statements ever come true? What if it skips the first, second and third one. What will it then return? It's an int function, it has to return an integer.
So is this better ?? I just added return 0 on the end of the function.

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
27
28
#include <iostream>

using namespace std;

int A(int n, int m)
{
    if(n == 0)
    {
        return m + 1;
    }
    if(m == 0 && n > 0)
    {
        return A(n - 1, 1);
    }
    if(n > 0 && m > 0)
    {
        return A(n - 1, A(n, m - 1));
    }
    return 0;
}

int main()
{
    int n, m = 0;
    cout << "Enter n and m: " << endl;
    cin >> n >> m;
    cout << A(n,m);
}
Last edited on
Hi,

The compiler confirms what TarikNeaj has said:

In function 'int A(int, int)': 
19:1: warning: control reaches end of non-void function [-Wreturn-type]


So it's a good idea to have the compiler warning options at their highest. :+)

Good Luck !!
Hey,

I think i solved the problem. I just changed line number 27 to:
 
cout << A(m,n);


Now it is not giving an endless loop. I guess the second number must be higher than the first number, that's all. :)
Thanks TarikNeaj and TheIdeasMan for help. :)
Don't you think it would make more sense to fix your function, so that it can correctly handle a situation where the second number is lower that the first?
What do you mean MikeyBoy ? You mean that it should ask a user to repeat the input if input is wrong ?
Topic archived. No new replies allowed.