C++ Recursive Final Exam Review - c++

While studying for my upcoming final exam I came across this review question, I know the answer when I call test_b(4) is: 0 2 4. My question is why it prints the 2 and 4 after the 0 if the first test_b(n - 2) comes before the cout?
void test_b(int n)
{
if (n>0)
test_b(n-2);
cout << n << " ";
}

Think about calls in a V shape:
test_b(4)
| //>0, so enter the if
| test_b(2)
| | //>0 so enter the if
| | test_b(0)
| | | //==0, so skip if
| | | print 0 // from the test_b(0)
| | | return
| | print 2 // from test_b(2)
| | return
| print 4 // from test_b(4)
| return
// end
The result is shown as printed, first the 0, then the 2, finally 4: 0 2 4.

Briefly, nothing is printed until (n > 0) is false, and the recursion block is hit.
You get the output, from 0 and effectively increasing by 2, as the stack unwinds.
A line by line debugger is always helpful when looking at stuff like this.

Evaluation of test_b(4) generates three nested calls. In the first call, the condition is true, so it makes the second call; in the second call, the condition is true, so it makes the third call. In the third call, the condition is false - at that level n=0 - so it skips directly to the output and prints IT'S value of n, i.e 0. Then the third call returns up to the second call - for which n=2 - and continues to the output and prints 2. Then the second call returns up to the first call - for which n=4 - and continues to the output and prints 4. Then the first call ends.

Because it reaches the print statement only when the if statement is false, i.e. n <= 0. After that it prints the values of n backwards, with respect to the recursive calls.
Perhaps it would be more clear if the code is presented like so:
void test_b(int n)
{
if (n > 0)
{
test_b(n - 2); // II: execution resumes from here for the rest n's
}
cout << n << " "; // I: this line is reached first when n <= 0
}

Recursive functions work exactly like all other functions.
(I think this is the most crucial thing to understand about recursion.)
So, let's get rid of the recursion by specialising the function into several.
These functions are equivalent to your "recurse first" implementation:
void testb_0()
{
cout << 0 << " ";
}
void testb_2()
{
testb_0();
cout << 2 << " ";
}
void testb_4()
{
testb_2();
cout << 4 << " ";
}
and these are equivalent to your "print first" implementation:
void testa_0()
{
cout << 0 << " ";
}
void testa_2()
{
cout << 2 << " ";
testa_0();
}
void testa_4()
{
cout << 4 << " ";
testa_2();
}
I'm convinced that you understand how these are different.

One way to imagine how this works is to do a series of replacements and simplifications.
We start with test_b(4). That can be replaced with the body of test_b, except we replace n with 4.
if (4>0)
test_b(4-2);
cout << 4 << " ";
We know that 4>0 is true and 4-2 == 2 so we can simplify to:
test_b(2);
cout << 4 << " ";
Then we substitute again:
if (2>0)
test_b(2-2);
cout << 2 << " ";
cout << 4 << " ";
You can repeat the simplification and substitution steps until you arrive at the final solution.

Related

what does the return statement without an expression do as in code below [duplicate]

This question already has answers here:
C++ "return" without value [closed]
(7 answers)
Closed 6 months ago.
I couldnot find a logical reason as how this return statement is working. As much as i read,it should return undefined but the program takes it straight to the recursive call
function below
#include <iostream>
using namespace std;
// Recursive function to print the pattern without any extra
// variable
void printPattern(int n)
{
// Base case (When n becomes 0 or negative)
if (n ==0 || n<0)
{
cout << n << " ";
return;
}
// First print decreasing order
cout << n << " ";
printPattern(n-5);
// Then print increasing order
cout << n << " ";
}
// Driver Program
int main()
{
int n = 16;
printPattern(n);
return 0;
}
the output of above code is
16 11 6 1 -4 1 6 11 16
Recursion isn't special. Here's your function again, but I hid the name so you can't see which function it is.
void XXXXXXXXXX(int n)
{
// Base case (When n becomes 0 or negative)
if (n ==0 || n<0)
{
cout << n << " ";
return;
}
// First print decreasing order
cout << n << " ";
printPattern(n-5);
// Then print increasing order
cout << n << " ";
}
What does XXXXXXXXXX(-1) do? That's right: it prints -1
What does XXXXXXXXXX(16) do? That's right: it prints 16, then it prints the pattern for 11, then it prints 16 again.
Now can you see why XXXXXXXXXX(16) prints 16 at the start and the end?
return (irregardless if the function is recursive or not) will pass an optional value to caller, and execution will then continue in caller.

Why does my recursive function print in descending order and then in ascending order?

I have a simple recursive c++ program and I am trying to understand exactly how it works. I understand why the program prints out 3 2 1, but then I don't understand why it goes the other way and prints 1 2 3. I used a hand-simulation and walked through the program step-by-step but still don't understand how the 1 2 3 comes about. I found this article from GeeksForGeeks but am still having difficulty grasping the concept. Any explanation would be awesome.
#include <iostream>
using namespace std;
void test(int n)
{
if (n > 0)
{
cout << n << " ";
test(n - 1);
cout << n << " ";
}
}
int main()
{
test(3);
return 0;
}
The order of function calls in your recursion looks something like this:
test(3)
-- cout << 3 << " ";
-- test(2)
-- -- cout << 2 << " ";
-- -- test(1)
-- -- -- cout << 1 << " ";
-- -- -- test(0)
-- -- -- cout << 1 << " ";
-- -- cout << 2 << " ";
-- cout << 3 << " ";
Change your program to
#include <iostream>
using namespace std;
void test(int n)
{
if (n > 0)
{
cout << "enter" << n << " "; // <- add "enter" here
test(n - 1);
cout << "exit" << n << " "; // <- add "exit" here
}
}
int main()
{
test(3);
return 0;
}
and you will see next output
enter3 enter2 enter1 exit1 exit2 exit3
You can think about recursive calls as operations with a stack.
There are two operations: push and pop.
What your program does is
push test 3
push test 2
push test 1
pop test 1
pop test 2
pop test 3
On every push and pop you do cout and thus see the output 3 2 1 1 2 3.
Here you can find more about recursion.
The thing is that all the answers don't help you because even if someone got it explained to you, you will stuck in the next algorithm.
I am offering a fundamental approach that helped me a lot with understanding some search algorithms, linked lists, binary trees and much more because I am a simple mind.
What you have to do is figuring out ways to represent the data in the most creative ways you can come up with. Because programming is just flipping data in lots of ways. A few examples I came up with is using plastic cans and post its or grapes and plates, I've seen some indian video guys that draw the data flow on charts or just with circles on a sheet of paper with different colors if you want
and that works as follows:
put the data on the post its, one for each round. You got a simple algorithm and I would write a "3" because it is passed through the function.
The jars, represent the function calls, I would take a jar for every call.
Simulate the algorithm bit by bit. Like taping the 3 on the jar -> first cout "3" -> test get called "n - 1" so "2" goes in a new jar (writing 2 on the post it)
-> second cout "2" -> test get called "n - 1" so 1 goes again in a new jar. (writing 1 on the post it)
->third cout "1" -> test get called "n - 1" so 0 goes in a new jar. (writing 0 on the post it) - but wait! 0 is not bigger as 0! So that jar won't pass the if command! so the test doesn't gets called again - function over.
Now look at your place! you got still 4 jars and the second cout in the function is not even called once - now its time because every jar represents one function call that is not finished and still open. what number is in the jar you put in last? Right, a 1! So "1" get to the cout. Crumple the post it, put the jar back. What is in the next jar? a "2"? bingo - that is printed through the second cout. The last cup has a 3 in it? - right, print it with cout than crumple the post it up. No cups anymore? No data to print out? you done!
Thats how the program works!
Congrats, because I am sure you grasped it now! :)
Btw. if you come to a point where you don't know where the data flows, every good IDE has a debugger that let you run exactly the steps the program does and it stops after every step. It is really good explained how to use a debugger in alex allain "jump to c++" and he has a whole chapter on how to read and write a program, also a whole chapter about recursion and i think 6 for pointers alone. He gave the tip to find ways to represent data and I hope that helps you as much as it helped me :)
Cheers
It's because you have the cout statement after calling the "test" method in your if-statement. After it walks down all the method calls and hits the base case, it then returns out of each of those method calls moving on to the next line (the cout statement) in the reverse order the methods got called in.
To make it clear rewrite the function
void test( unsigned int n )
{
if ( n )
{
std::cout << n << " ";
test( n - 1 );
std::cout << n << " ";
}
}
the following way
void test( unsigned int n )
{
if ( n )
{
std::cout << n << " ";
std::cout << n << " ";
test( n - 1 );
}
}
That is move the second statement
std::cout << n << " ";
above the statement
test( n - 1 );
For the call test( 3 ); of the modified function you will get the following output
3 3 2 2 1 1
So each recursive call of the function two times outputs the passed value n. I hope it is clear because the function explicitly contains the same statement two times
std::cout << n << " ";
std::cout << n << " ";
Now returning to the original function definition we see that between the two outputs of the same value n the function calls itself with the value n - 1.
So each function call outputs the same value two times but between the outputs the function calls itself recursively.
Now the output can look like
3 3
|
call itself for 2
... and so on.

Regarding Recursive Functions in C++ (Beginner Level)

So I've just started C++ programming, and am a little stuck on one particular program that was used to demonstrate how recursive functions work. I do know the premise of recursive functions, that being a function which calls itself until an exit condition has been met. I understood the concept using the program for factorials,
int factorial(int n)
{
if (n==1)
{
return 1;
}
else
{
return n*factorial(n-1);
}
}
the if statement being the exit condition in the above code.
However, the code that tripped me up was from this link:
http://www.cprogramming.com/tutorial/lesson16.html
specifically this code:
#include <iostream>
using namespace std;
void printnum ( int begin )
{
cout<< begin<<endl;
if ( begin < 9 ) // The base case is when begin is greater than 9
{ // for it will not recurse after the if-statement
printnum ( begin + 1 );
}
cout<< begin<<endl; // Outputs the second begin, after the program has
// gone through and output
}
int main()
{
printnum(1);
return 0;
}
OP:
1
2
3
4
5
6
7
8
9
9
8
7
6
5
4
3
2
1
In the immediately above code, I understand the output till the first 9. But after that, why does the cout statement following the if loop cause the begin variable to start counting backwards till it reaches the value it originally was when printvalue was first called? I suppose I don't really understand the exit condition here.
Not sure what I'm missing, and any help would be greatly appreciated.
Thanks.
Each begin is unique and belongs to the "current" active function – its value never changes.
Recursive functions work exactly like other functions; it doesn't matter to one what the parameter of another is named.
If you had these:
void f(int x);
void g(int x)
{
cout << x << endl;
f(x+1);
cout << x << endl;
}
you would be very surprised (I hope) if g printed two different numbers.
Your recursion works exactly like this (much smaller) example that uses unique functions instead of recursion with a parameter:
void printnum_3()
{
cout << 3 << endl;
cout << 3 << endl;
}
void printnum_2()
{
cout << 2 << endl;
printnum_3();
cout << 2 << endl;
}
void printnum_1()
{
cout << 1 << endl;
printnum_2();
cout << 1 << endl;
}
int main()
{
printnum_1();
}
So, lets see what happens when printnum(1) is called.
begin equals 1, it is printed with cout and then printnum(2) is called.
But what happens when the program leaves printnum(2) function? It continues to execute printnum(1) from the place, where printnum(2) was called. So, the next line to execute is cout << begin. begin still equals 1, because we are executing printnum(1) function. This is why 1 is printed once again at the end. The situation is totally the same with other function calls.
For example, when printnum(9) is called, it prints 9, then the if check fails (begin is not less, than 9) and then 9 is printed once again.
why does the cout statement following the if loop cause the begin variable to start counting backwards till it reaches the value it originally was when printvalue was first called?
To start with, there is no loop. There is call stack which you need to understand. Recursive call stops when (begin < 9) becomes false i.e. when begin = 9. You are seeing the call stack unwinding.
First cout in the function is printing sequence [1..9], and second cout is printing the decreasing sequence [9..1].
Your code execution is like this:
cout<< 1 <<endl; //enter1
cout<< 2 <<endl; //enter2
cout<< 3 <<endl; //enter3
...
cout<< 8 <<endl; //enter8
cout<< 9 <<endl; //enter9
cout<< 9 <<endl; //exit9
cout<< 8 <<endl; //exit8
...
cout<< 3 <<endl; //exit3
cout<< 2 <<endl; //exit2
cout<< 1 <<endl; //exit1

Recursion with functions in C++

I have problem understanding this code:
#include <iostream>
using namespace std;
void Print_numm(int numm){
cout<<numm;
if (numm<=4) {
Print_numm(numm+1);
}
cout<<numm;
}
int main() {
Print_numm(1);
return 0;
}
The output is 1234554321.
I understand the recursion up until it prints 123455. But why the compiler prints the rest of of numbers down to 1? Does the compiler do the second "cout" every time? And if so how it keeps the numbers until they are printed up to 5 and then prints the rest downward?
If you visualize the execution of the call it will be easier to understand:
Print_numm(1)
-> cout 1
-> Print_numm(2)
--> cout 2
-->Print_numm(3)
---> cout 3
---> Print_numm(4)
----> cout 4
----> Print_numm(5)
-----> cout 5
-----> cout 5
----> cout 4
---> cout 3
--> cout 2
-> cout 1
Are you familiar with a stack?
The function calls itself,and prints every number upwards,then it returns from the final recursive call,going downwards through the numbers,as it return from recursion repeatedly.It just executes the rest of the code that it contains after the recursive call.
A simple representation of this is:
print_numm(1):
cout << 1
print_numm(1+1):
cout << 2
print_numm(2+1):
cout << 3
print_numm(3+1):
cout << 4
print_numm(4+1):
cout << 5
//now the number is bigger than 4 so the function
//will return from recursion
cout << 5
//now the function is done,but the function that called print_numm(5) is waiting to finish
//so it executes the rest of the code printing 4,same with all waiting for print_numm(4) and so on
cout << 4
cout << 3
cout << 2
cout << 1
Here's how the code get's executed, you can easily tell this way why you get the output in discussion:
Print_numm(1)->
cout<<1
Print_numm(2)->
cout<<2
Print_numm(3)->
cout<<3
Print_numm(4)->
cout<<4
Print_num(5)->
cout<<5
cout<<5
cout<<4
cout<<3
cout<<2
cout<<1
The second cout is placed after the recursive call, this means that it will get executed after all the inner calls return.
You can see that it would do this (assuming it returns).
cout<<1;
Print_numm(2);
cout<<1;
which can be expanded to:
cout<<1;
cout<<2;
Print_numm(3);
cout<<2;
cout<<1;
and then eventually output "1234554321".
Since the condition numm<=4 become false at numm=5.
Therefore numm stops incrementing and rest of the code of the previously calling functions executed.
The function recurses from 1 to 5, and these numbers are output in the first call to cout << numm (the first line of the Print_numm function. Once the if statement evaluates to false the recursion starts to unwind, and as the calls to Print_numm return they encounter the final cout << numm line on the last line of the function and print from 5 to 1.
The execution would be easier to visualize if you added some extra diagnostics to your code. Consider this change:
#include <iostream>
using namespace std;
void Print_numm(int numm){
cout << "enter: " << numm << endl;
if (numm<=4) {
Print_numm(numm+1);
}
cout << "exit: " << numm << endl;
}
int main() {
Print_numm(1);
return 0;
}
Which produces:
enter: 1
enter: 2
enter: 3
enter: 4
enter: 5
exit: 5
exit: 4
exit: 3
exit: 2
exit: 1
You can also use a debugger to step through to help you understand this better.
One important code understanding principle. Adding good diagnostics greatly decreases the amount of mental effort and aptitude required to understand what is happening.

c++ Recursion array explanation

Hello i am learning recursion and currently i have couple of trick problems to dissect - here is one of recursive functions
int rec(int niz[], int start, int end){
if (start == end)
{
return niz[start]; // vraca zadnji
}
int temp = rec(niz, start+1, end);
// control output
cout << "\n-----\n";
cout << "start " << start << endl;
cout << "niz[start] " << niz[start] << endl;
cout << "end " << end << endl;
cout << "temp " << temp << endl;
cout << "\n-----------------------------------------\n";
//contrl output end
return ((niz[start] < temp) ? niz[start] : temp);
}
i included a cout block to control what is gong on in calls. here is main part
int niz[] = {1,2,3,4,5,6,7};
cout << rec(niz, 0, 3);
and here is my output:
-----
start 2
niz[start] 3
end 3
temp 4
------------------
-----
start 1
niz[start] 2
end 3
temp 3
------------------
-----
start 0
niz[start] 1
end 3
temp 2
------------------
1
can anyone explain me how is temp value being calculated and returned and how i am getting 1 as the return of this function?
Thank You in advance!
Recursive function is the function that calls itself.
int temp = rec(niz, start+1, end);
Here you call the "rec" function inside the one, but with the changed parameter (start + 1). You call these function inside each other until the "start" equals "end" (then it returns)
if (start == end)
{
return niz[start]; // vraca zadnji
}
After the deepest one returns the second deepest one continues its flow, printing some information.
cout << "\n-----\n";
cout << "start " << start << endl;
cout << "niz[start] " << niz[start] << endl;
cout << "end " << end << endl;
cout << "temp " << temp << endl;
cout << "\n-----------------------------------------\n";
Then it it returns the lowest value between niz[start] and temp (local values).
return ((niz[start] < temp) ? niz[start] : temp);
Then the third deepest one continues its flow and so on. Until it gets to the first function.
In your main part you set the end to 3, so it performs the operation on the first 3 elements (it gets to the fourth element, but doesn't do anything beside returning its value). You get 1 by comparing the niz[0], that you passed as start, and temp that is returned by recursive function (which happens to be the same). It equals, so the return value is niz[0] that is 1;
When using recursive functions, you should have some kind of "exit point" that prevents the recursion to become infinite, i.e.
if (start == end)
{
return niz[start];
}
In general, recursive functions look like this:
f()
{
//return condition
//some work
f();
//some work
//return
}
And you can look at them as this
f()
{
//some code
f()
{
//some code
f()
{
//some code
f()
{
...
//eventually the return condition is met
}
//some code
//return
}
//some code
//return
}
//some code
//return
}
Keep in mint that unhandled recursion may lead to possible memory leaks, because each function call comes with additional data.
f()
{
f();
}
This will lead to stack overflow due to system data that has been created;
You may want to watch "Inception" to understand it better :)
rec(niz, 0, 3) (D)
|
---->rec(niz, 1, 3) (C)
|
----> rec(niz, 2, 3) (B)
|
----> rec(niz, 3, 3) (A)
You call (D) which calls (C) to calculate temp and so on up to (A). In (A) start==end and it returns niz[3]=4.
In (B):
temp = 4 (result of (A))
start = 2
As 4 is bigger than niz[start]=3 (B) returns 3
In (C):
temp = 3 (result of (B))
start = 1
As 3 is bigger than niz[start]=2 (B) returns 2
In (D):
temp = 2 (result of (C))
start = 0
As 2 is bigger than niz[start]=1 (B) returns 1
Your recursive line is before your print statement block. By nature of recursion, it makes the function call on that recursive line and stops the caller function's execution until the callee is done. Therefore you call for the next element to be processed before you print the current element.
In your example the following is happening:
Layer 1:
Is start equal to end? No.
What is the result of the next element? Don't know yet, recurse.
Layer 2:
Is start equal to end? No.
What is the result of the next element? Don't know yet, recurse.
Layer 3:
Is start equal to end? No.
What is the result of the next element? Don't know yet, recurse.
Layer 4:
Is start equal to end? Yes!
Return the current element, 4.
End layer 4.
Layer 3:
Now know next element, start printing for the 3rd element.
Return 3.
End layer 3.
Layer 2:
Now know the next element, start printing for the 2nd element.
Return 2.
End layer 2.
Layer 1:
Now know the next element, start printing for the 1st element.
Return 1.
End layer 1.
End program.
As you can see, the array elements are printed backwards because the print statements are after the recursive call. I'd you want them to be printed in order, print them before the recursive call, or create a buffer and append each print section to the front of the buffer.