Function not breaking out on encountering return - c++

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.

Related

c++ debugging a recursive function and it doesn't exit the function right away

If I put a break point on this function it will step through until the base case is met but when it hits the return 1 it doesn't actually exit the loop. Instead it goes to the bottom bracket and then bounces to int t = expo(m, n / 2) and steps downs to return t * t*m. It then goes back to the bottom bracket and repeats this process before eventually stopping. Can someone explain what is going on?
int expo(const int m, const unsigned int n) {
funcCallCounter++; //counts how many times the function is called
if (n == 0) {
return 1;
}
else {
if (n % 2 == 0) {
int t = expo(m, n / 2);
return t * t;
}
else {
int t = expo(m, n / 2);
return t * t*m;
}
}
}
When the flow of your program in a function encounters a return statement, control is returned to place that called that function. That is true even if it was the same function. This is completely normal and expected.
In your case, each call still has work to do after the recursive step (because your expo() call is never quite the last thing before return) and you're seeing the program get on with that work.
Keep an eye on your stack frame while debugging; you'll see that it's not really jumping around in the way that you think it is; you're returning to previous call contexts.

How are return results computed in a recursive function?

I thought up to this point in time, that I understood how a return works, but once I got into the recursions, I suppose I'm a bit more lost than the originally thought.
Suppose, I have a function for count, that how many times a char pops up in a string.
int frequency(char ch, string input, int pos) {
if (pos == inputString.length()) {
return 0;
}
if (inputString[pos] == ch) {
return 1 + frequency(ch, inputString, pos + 1);
}
else {
return frequency(ch, inputString, pos+1);
}
}
If I were to pass to it, the string "Jeff" and looking for "f", it returns a value of 2.
So, how does it know when to stop?
Does return 0 end any method with return type int?
And if so, why does it still return the value of 2, when the final return says return 0?
The last return
return 0;
is only the last time the function is called during the recursion. This is needed to stop the recursion at some point. For the call before this last one one of the other return statements is executed, e.g:
return 1 + frequency(ch, inputString, pos + 1);
Thus the 0 is added up to the 1 and any previous results of the recursion.
PS:
As long as the function return statement calls the function again the recursion continues. Only when the return simply returns something (without calling the fucntion again) the recursion stops.
Here is a more simple example that calculates the sum of all integers up to N:
int calcSum(int N){
if ( N == 1 ) return 1; // recursion stops here
return N + calcSum( N-1 ); // otherwise continue to add up
}
Multiple return statements in one function are not special to recursion. The function just returns on the first return it encounters.
So, how does it know when to stop?
When no more recursive calls are added from a particular branch in the recursively called function it will stop, and the call stack will be cleared with returning values in the reverse order of the calls were issued (LIFO). That's done here:
if (pos == inputString.length()) {
return 0;
}
Any of the other branches call the function recursively and take a step down in the call stack:
if (inputString[pos] == ch) {
return 1 + frequency(ch, inputString, pos + 1);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
else {
return frequency(ch, inputString, pos+1);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
Does return 0; end any method with return type int?
Yes, and it will do for any return types that can be initialized with 0
And if so, why does it still return the value of 2, when the final return says return 0?
Because the results of the recursive call results were accumulated on the stack:
return 1 + frequency(ch, inputString, pos + 1);
// ^ the result of the operation will be saved on the stack when the call returns
... and you see the final result of the (first) recursive call in your driver function.
BTW, the much cheaper implementation by means of performance and memory usage would be a simple loop. There aren't any drawbacks regarding the linear time behavior anyway:
int frequency(char ch, string input) {
int result = 0;
for(int pos = 0; pos < input.size(); ++pos) {
if (input[pos] == ch) {
++result;
}
}
return result;
}
Think of a recursive calls as a stack of function calls. At some point it may hit return 0; This mean that one of the function calls on the stack is completed. Thus an element on the stack is popped. The function's final return happens when the stack is empty.

bool returning recursive function alters variable unexpectedly

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.

Explain the program flow in this C++ function

I wrote a strange function to find the factorial of a number
int strange_fact(int n=0)
{
static int i=n;
static int j=i;
if(j>1)
{
i *= --j;
strange_fact();
return 0x7777; //<------ This line
}
else
return i;
}
When I commented the 9th line, I was getting the expected output. But I encountered a strange (or maybe not so strange) behaviour after adding that line. What happens when I uncomment it is that program flow reaches line 9 even though a recursive function call precedes it. My question is, how does flow reach line 9?
When recursive call to function ends, line 9 will be reached. See this (shorter) example:
int foo(int i) {
if(i > 0) {
foo(i-1);
return 0x7777;
} else {
return i;
}
}
So when calling foo(1) it will go through first if (because 1 > 0) and foo(0) will be called. Now inside this call (foo(0)) program will go into else barnch (because 0 is not > 0) and foo(0) will return 0. So now we will be back to our first call (foo(1)) and as foo(0) returned, foo(1) will return 0x7777.
This line
strange_fact();
does the recursion and throws away the result.
The next next line
return 0x7777;
will return that value finally.
If you remove that line and compiled with the warnings on it will inform you that all paths do not return a value
You need to understand how recursions work.
After calling strange_fact() you've put a return statement. Meaning once the function is executed, it's still going to return 0x7777, which screws the answer up.
Check this out, this should work as expected:
int strange_fact(int n=0)
{
static int i=n;
static int j=i;
if(j>1)
{
i *= --j;
strange_fact();
// return 0x7777; // We don't want to return a value yet
}
if(j<=1) // We need to check this condition after strange_fact is executed
return i;
// This line will never be executed
return 0x7777; //<------ This line
}
If you eliminate the static variables, you'll get something like this:
long fact(long i)
{
if(i > 0)
return i * fact(i-1);
if(i == 0) // factorial(0) = 1
return 1;
throw exception("Negative numbers cannot have factorials"); // Or you can handle it by returning a -ve error code
}
The whole thing, explained by a diagram
Let us consider the case of strange_fact(3)
So, whatever happens in the recursive steps becomes meaningless because ultimately, 0x7777 will be returned when the control comes back to the first call.

Not fulfilling If condition but the function still return something

Below is the code :
The Code :
#include <iostream>
using namespace std;
int sum(int ); //To sum up the user input up to 1 , for e.g 4 = 4 + 3 + 2 + 1 = 10
int main(void)
{
int num;
int total;
cin >> num;
total = sum(num);
cout << total;
return 0;
}
int sum(int num)
{
if(num > 0) // How if num is -1 or -10??
return num + sum(num - 1);
}
The Question :
1.) I try to execute the above code and input value that violate the if condition for e.g -1 or -100 . But still when I cout the total variable I get back the value I've given to the variable num .
2.) My question is , is this a standard behavior ? Because I can run this code without getting any warning or error saying there's no return statement stated I don't have an extra return statement in case the num is violating the condition . So is this returning- the-original-value-if-the-condition-is-not-true something normal or it depends on the compiler being used ?
THank you .
A function that promises to return a value and does not induces Undefined Behavior (in C, only if the value is used).
Here your function has two executions paths:
int sum(int num) {
if (sum > 0)
return num + sum(num - 1); // code path 1
// code path 2
}
And in the second code path, it does not return anything.
Undefined behavior means anything can happen. The popular image is that daemons could start flying out of your nose. In practice, you are more likely to get a more or less random value depending on the implementation. Looks like in your case, for your compiler, this program and that set of optimizations (and maybe because the stars aligned, too) you get num. Lucky you.
By the way, my compiler gives a warning:
source.cpp: In function 'int sum(int)':
source.cpp:22:1: warning: control reaches end of non-void function [-Wreturn-type]