Recursive help

Hi, I'm not understanding why my recursive function returns False.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

bool timer(int attack, int calm, int worker){ //2, 3, 9 goes in
     
    if (worker - attack <= 0){ //will 9 - 2 = 0 or less? 
        return false;
    }
    
    worker = worker - attack; //9 - 2 = 7
    
    if (worker - calm <= 0){ 
        return true;
    }
    
    worker = worker - calm; // 7-3=4
     
    return timer(attack, calm, worker); // 2, 3, 7
}


Shouldn't 9, 2, 3 return true?
9 would go to 7, then 7- 3 would go to 4
4 isn't less than 2, so it would become 4-2= 2.
2-3 is -1, which is less than 3, so why wouldn't it return true?

It's returning false for me.

I must not be understanding recursion.
Can someone help me out?

Thank you.
I posted the code you provided.

I ran it with parameters 2, 3, 9.

It returned true.

However, to be clear, the final recursive call to timer passed parameters 2, 3, 4, not 2, 3, 7
Last edited on
Looks like the confusion could be between "2, 3, 9" as it says in the first code comment and "9, 2, 3" which is how it's said in the question. The second one does return false.
It returned true for you? hmm

Maybe the problem for me is somewhere else.

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
32
#include <iostream>

using namespace std;

bool timer(int attack, int calm, int worker){ //2, 3, 9 goes in
     
    if (worker - attack <= 0){ //will 9 - 2 = 0 or less? 
        return false;
    }
    
    worker = worker - attack; //9 - 2 = 7
    
    if (worker - calm <= 0){ 
        return true;
    }
    
    worker = worker - calm; // 7-3=4
     
    return timer(attack, calm, worker); // 2, 3, 7
}

int main(){
    
    int d1a, d1c, d2a, d2c;
    int p, m, g;
    cin >> d1a >> d1c >> d2a >> d2c;
    cin >> p >> m >> g;
    
bool x = timer(d1a, d2c, p);
bool xx = timer(d2a, d2c, p);
cout << x << endl;
cout << xx << endl;


Is there anything that would make 2, 3, 9 return false?

>> Dutch
My mistake. I just got turned around a bit, but I run it 2, 3, 9.
Should the middle argument of the first timer call be d1c ?
..............

yes.
haha.

Thanks dutch.
...descriptive names...I read that somewhere....
Registered users can post here. Sign in or register to post.