bool returning recursive function alters variable unexpectedly - c++

Could someone explain to me what happens in this? From the little knowledge I have(and clearly I am wrong in my thinking), to me this should keep decreasing x by 1 until x is 3. Then it should go to the 'return true, part and as the function returns true, it goes back to the second if statement, return false and then exit the function since there is nothing to do if the function returns false. But this keeps going back to the second if statement adding 1 to x until it is 9 again and then exits. Thanks in advance.
bool Rec(int x)
{
if( x > 3)
{
if(Rec(x - 1) == true)
{
return false;
}
else
{
return false;
}
}
else
{
return true;
}
}
void main()
{
Rec(9);
}

Actually I don't see a problem with the way your code functions. It actually works.
It can be simplified and is equivalent to:
#include <stdio.h>
bool Rec(int x)
{
printf("x = %d\n", x);
if (x > 3)
{
Rec(x - 1);
return false;
}
return true;
}
int main(int argc, char* argv[])
{
Rec(9);
return 0;
}
Which produces:
x=9
x=8
x=7
x=6
x=5
x=4
x=3
However you've also said: "But this keeps going back to the second if statement adding 1 to x until it is 9 again and then exits". But you're not actually adding 1 to x. I think what's going on is to do with your debug. You haven't put any debug in your code to print out said behaviour.
So I'll attempt to do it for you.
bool Rec(int x)
{
printf("x = %d\n", x);
if (x > 3)
{
Rec(x - 1);
printf("*x = %d\n", x);
return false;
}
return true;
}
Which produces:
x = 9
x = 8
x = 7
x = 6
x = 5
x = 4
x = 3
*x = 4
*x = 5
*x = 6
*x = 7
*x = 8
*x = 9
Think about this carefully. You're not adding 1. Your function is calling itself again printing x = and then if it's greater than 3 doing the same. Only when x > 3 does it return. After it returns it will again print *x =
So it's actually printing what x was before the recursive call. I hope that helps you see what's going on.
Your function is fine to see how recursion works. But in practice you'd never write code like that. Because you could just write it as a simple loop.
Avoid recursion if you can come up with code using a loop. But sometimes, recursion is easier. For example, traversing binary trees is really simple with recursion.
There are some answers on this question here which give real world examples of where recursion makes sense. Real-world examples of recursion

This is the nature of the recursion. You called function 6 times, it is going to return 6 times.

Related

Function not breaking out on encountering return

int min_steps(int target, int move)
{
int x,y,z;
cout<<target<<" "<<move<<endl;
if(target==move || target+move==0)
{
return 1;
}
x = 1 + min_steps(target-move,move+1);
y = 1 + min_steps(target+move,move+1);
z = x<y?x:y;
return z;
}
int main() {
cout<<min_steps(3,1);
return 0;
}
In the above recursive function min_steps, the cout statement has been included to track the recursive calls. Now min_steps(3,1) encounters a call where target=2 & move=2, in which case the if condition holds True & therefore the function is supposed to return 1 & break. But this is not happening. The function is continuing to make calls and thus resulting in Time limit exceeded error
The problem lies in these two lines:
x = 1 + min_steps(target-move,move+1);
y = 1 + min_steps(target+move,move+1);
While as you said, the first line did return, the second line doesn't return at all. It would keep calling (4,2) -> (5,3) -> ... and cause a stack overflow error (0xC00000FD), unless in your input the if statement is already satisfied.
So to fix this you need to add more condition or change the second line probably.

problem with returning from function in c++/c

i have this problem with returning from function.
it's a search function, it should return 1 if the function find the value that i give but No, it's returning the 0 instead of 1. (sorry for my bad english.)
int rech(int tab[],int n,int i,int r){
if(i<n){
if(tab[i]==r){
return 1;
}
i++;
rech(tab,n,i,r);
}
return 0;
}
int main(int argc, char** argv) {
int tab[5]={1,2,3,4,5};
printf("%d",rech(tab,5,0,2));
return 0;
}
Let's walk through it together.
When rech gets called the first time:
First time we call rech:
rech(tab = {1,2,3,4,5}, n = 5, i = 0, r = 2)
is i < n or 0 < 5? This is true.
Now we check if tab[i] == r or 1 == 2. This is false.
We increase i and start over again
Second time we call rech:
rech(tab = {1,2,3,4,5}, n = 5, i = 1, r = 2)
is tab[i] < r or 1 < 5? This is true.
Now we check if tab[i] == r or 2 == 2. This is true.
We return 1 back to the first time rech got called.
Back to the first time we call rech:
rech(tab, n, i, r) returned 1. So, in coding terms this would
look like 1; which does nothing.
Now we are done with the if statement and return 0 to main.
main now prints out a 0 and the program ends.
This is the process of debugging the code.
To have the program return the 1 back to main instead you'll want to have it return the rech function because otherwise, the recursive call does nothing.
When you use return you will return to the caller, which in a recursive function will mean the same function most of the times.
Change
rech(tab,n,i,r);
to
return rech(tab,n,i,r);

I don't understand why I need to put two lines in a specific order for it to work (recursion)

I just started to learn about recursion.
This program is supposed to calculate n! and store the result into an output parameter.
void factorial(int n, int &f)
{
if (n == 0)
{
f = 1;
}
else
{
factorial(n - 1, f);
f *= n;
}
}
int main()
{
int f;
factorial(5, f);
cout << f;
}
This way it works perfectly. In my first attempt, the else condition looked like this
else
{
f *= n;
factorial(n - 1, f);
}
and the program didn't output anything but 1.
I really can't understand why it works in the first way but in the second it doesn't. Can you explain to me?
In your code, factorial(0, f) will set f = 1. If you modify f before the call to factorial, it will be overwritten.
Note that this problem is not possible if you return int instead of taking int & as an argument.
For anyone wondering:
Using #ForceBru's suggestion I ran it on a piece of paper and I got it. If I do it in the second way, the last thing called will be factorial(0) which will return 1, even if I already calculated to be n!.
f is getting over written to 1 in your last call f(0). If you switch the statements then f gets initialized to 1 in the last call f(0) followed by It's modification before return of each function call

staircase child always getting a 0?

Hi I am a beginner in recursions.
Question:
A child is running up a staircase he can hop 1, 2 or 3 steps at a time I need to find and return the number of ways he can climb a certain stair number?
My approach:
I am trying to divide the problem into smaller base cases and add 1 when a correct ans is reached.
My code:
void helper(int n ,int& a){
if(n==0){
a = a+1;
return;
}
if(n<0)
return;
helper(n-1,a);
helper(n-2,a);
helper(n-3,a);
}
int staircase(int n){
int ans = 0;
helper(n,ans);
return ans;
}
Problem:
I seem to be getting only 0 as answer?
I dont see why your code won't work. Here is a demo of it working with some changes: Live Demo
It is recommended that you don't pass in a reference and rather make each sub-problem which is either step 1, 2 or 3 self contained problems where you combine the results and that is the final answer similar to:
int staircase_without_reference(int n)
{
if(n == 0) return 1;
if(n < 0) return 0;
return staircase(n - 1) + staircase(n - 2) + staircase(n - 3);
}
This returns the similar to your program without the reference parameter.

C++ FAQ example on inline vs. #define

There is an example on the FAQ to explain the difference between inline and #define. The code is here
and the link is: http://www.parashift.com/c++-faq/inline-vs-macros.html
Tried with Visual C++, both unsafe() and unsafe(f()) didn't increase i twice. Is there a mistake on the example?
The main idea of #define is that it is just a preprocessor directive, meaning that this:
#define unsafe(i) ( (i) >= 0 ? (i) : -(i) )
will preprocess your code before it is compiled, and will replace the statement
unsafe(x++);
with the following
((x++) >= 0 ? (x++) : -(x++));
Everytime x++ is evaluated, x gets incremented.
One possible reason why you have problems with getting this sample code right might be that you compile your code with optimizations that optimize out all the unused / unnecessary code.
If you don't use your x anywhere, then it is considered as unused, hence does not get included into compiled code.
Just tested the example, Check Eric Gopak's answer for the explanation:
// A macro that returns the absolute value of i
#define unsafe(i) \
((i) >= 0 ? (i) : -(i))
// An inline function that returns the absolute value of i
inline
int safe(int i)
{
return i >= 0 ? i : -i;
}
int countCalls = 0;
int f()
{
return countCalls++;
};
int main()
{
int x = 0;
int ans = 0;
ans = unsafe(x++); // Error! x is incremented twice
ans = unsafe(f()); // Danger! f() is called twice
// x = 2
// countCalls = 2
ans = safe(x++); // Correct! x is incremented once
ans = safe(f()); // Correct! f() is called once
// x = 3
// countCalls = 3
return 0;
}