Recursion output - java

I was just introduced to recursion and I was given the following lines of code:
public class RecursionThree
{
public void run(int x )
{
if(x<5)
run(x+1);
out.println(x);
}
public static void main(String args[] )
{
RecursionThree test = new RecursionThree ();
test.run(1);
}
}
and the output is supposed to be: 5 4 3 2 1. I get why it would print 5 (because 5<5 would equal false and it would print x, which is 5). However, I do not understand why it prints 4 3 2 1 too. Thanks for your help

How recursion works is you break down to the base case and build up backwards. In your case. Your base case was x>=5, the point at which it would stop expanding the recursive tree, you can think of the base case as the end of the tree, or leaf. After that it goes back up completing things that were to be done after run was called. SO in your case, each time after calling one, it printed out x.
When x=1, it calls run(2), after run(2) is resolved, it would go to the next line. After run(2), the print out is 5 4 3 2 after that it would print out x coming back to the original call of run(1), which would be 1. This is really great for traversing trees etc and a lot of other problems.
To picture it, when you call run(1)
run(1)
1<5
run(2)
2<5
run(3)
3<5
run(4)
4<5
run(5)
print(5)
print(4)
print(3)
print(2)
print(1)
As you can see it goes to the base case, and back up.
To get familiar with recursion more, you can do problems like, finding the largest int in an array with the method head being public int findLargest(int [] array, int someNumber) where you would use someNumber to whatever you think you need. Or reversing a string using recursion and one parameter.

For your x=4 case, run(5) was called. After that completed running, control was returned to the callee function, where x is presently 4. So, it executes the line after the if which prints the 4.
The same logic follows for x = 3, 2, 1.

Related

I'm not sure why myst() works this way as a recursive method

public class Recur2 {
public static void main(String [] args) {
myst(4);
}
public static void myst(int a) {
if (a != 0) {
System.out.println("Before: " + a);
myst(a-1);
System.out.println("After : " + a);
}
}
}
The output should be:
Before: 4
Before: 3
Before: 2
Before: 1
After: 1
After: 2
After: 3
After: 4
But I'm not completely positive on why this works this way. What does the myst(a-1) accomplish in the middle of the code, and why does it go in ascending order afterward?
But I'm not completely positive on why this works this way.
It is a simple example of recursion in Java code. It works this way ... because this is how recursion works.
Recursion happens when a method calls itself.
What does the myst(a-1) accomplish in the middle of the code
That is the recursion. That is myst calling itself.
You will notice that myst is calling itself with an argument that is one less than the argument it was called with. So what happens is:
myst(4) calls myst(3)
myst(3) calls myst(2)
myst(2) calls myst(1)
myst(1) calls myst(0)
myst(0) doesn't recurse ... because a != 0 is not true!
... and why does it go in ascending order afterward?
Look where the print statements are. There is one print "on the way down" and another "on the way back up". And look at the expression that each is printing. It is a ... the local parameter ... for this call.
If it is still not clicking for you, think of a real world analogy. For example:
Imagine you in a room with a step ladder. Imagine that you have
climbed to rung 4 of a step ladder. Your plan is to go the bottom of
the latter and then back up to 4. You have a couple of rules.
Before you step down, you shout out "BEFORE" and then the current rung number.
After you step back up, you shout out "AFTER" and then the current rung number.
Q: What does someone in the next room hear?
A: "BEFORE 4" pause, "BEFORE 3" pause, "BEFORE 2" pause, "BEFORE 1" pause, "AFTER 1" pause, "AFTER 2" pause, "AFTER 3" pause, "AFTER 4".
This short snippet illustrates how does the concept of recursive function works.
The mist() function does not anything particular apart from calling itself recursively, this is the whole point.
Before and After prints help you understand the order of operations, first recursion goes deeper and deeper, and then it go back-up again (and thus this ascending order).
If this is still not clear, read some online articles of recursion in general - it should help.

Recursion - mystery1

Having a tough time with the below code, I have answered the first call correctly as the condition is immediately correct. However, the second call of 4 is causing me great confusion, I came to the answer 2, 1 however it is incorrect- I am clearly getting things mixed up. Can someone explain to me exactly why my answer is wrong and the correct breakdown of the process of Recursive tracing in this example. I do understand elements of recursion however I am having issues following the process of tracing.
public void mystery1(int n) {
if (n <= 1) {
System.out.print(n);
} else {
mystery1(n / 2);
System.out.print(", " + n);
}
}
mystery1(1);
mystery1(4);
mystery1(16);
Recursion is beautiful yet very powerful and when it comes to observe it, people get tricked.
Let me explain you how i learnt it when i was preparing for my GATE(Graduate Aptitude Test in Engineering).
Think of each Function call as 2 parts:
Printing
Calling with halving itself
Now all the operations will be stacked upon the older one until unless we are out of recursion and only Printing is left in the function cycle.
We will print out in stack format i.e FIFO
Example, if we have these elements in stack:
Top:
4
3
7
2
Bottom
It will print 4 3 7 2 .
Now taking your Question:
Lets break your Conditional statements in two halves, 1st will be if condition with Print 2nd will be else with its print.
Note: Only one part i.e 1st will print 1 and that too without commas (,).
I have attached the Image below kindly refer it, think as print statement as on stack, and the lowest print statement will be executed first as we will end out of function calls.
Now combining mystery1(1),mystery1(4),mystery1(16) the final output will be: 1
1
, 2
, 4
1
, 2
, 4
, 8
, 16
PS: If you are going to give interviews of Amazon , Google or any Reputed Product based company they will ask question with flavor of recursion and that too without using any compiler, they wanna test your concepts via programming.
When you call mystery1(4), it goes to the else part and calls mystery1(2) since n>1. The print statement will be executed only after mystery1(2) has finished executing.
The same thing happens for mystery1(2) and it calls mystery1(1). It waits for mystery(1) to finish execution.
When mystery1(1) is called, it prints "1".
Then, mystery1(2) will continue and print ",2".
Finally, mystery1(4) will continue and print ",4".
So your output will be 1,2,4
In your method:
public static void mystery1(int n) {
if (n <= 1) {
System.out.print(n);
} else {
mystery1(n / 2);
System.out.print(", " + n);
}
}
try to replace the position of System.out.print(", " + n); before mystery1(n / 2); call.
In the first case, when System.out after mystery1 call, you have result as 1, 2, 4, because, first you have to get result, then print it.
In the second case, when System.out before mystery1 call, you have result as , 4, 21, because, first you print the result, then calculate the next result in function.

Can anyone explain how this code prints 1 to 10?

Can anyone explain how this code prints 1 to 10???
class demo
{
public static void main(String[] args)
{
display(10);
}
private static void display(int n)
{
if (n > 1)
{
display(n - 1);
}
System.out.println(n);
}
}
It's a recursive call to display method. Here the argument value passed to display method is stored in a stack. when the if condition fails then the value of n if poped from stack and printed by line "System.out.println(n)".
In other words, Every time display method called by passing a number, the number will be stored in a stack so that when code will come out of recursion, it will use that number from stack.
Doing the dry run you can see when the value 1 is passed to display method the if condition fails and the next line prints the value 1 then 2 will be printed which was in stack and so on it will print up to 10 which is the first value passed.
So the main method runs the display method and passes a value of 10. Then, the value is checked to see if it is greater than 1 (which it is). Next. the display method is called again with a value of n-1, which is 9 in this case. Lastly, 10 is printed out.
Now 9 goes through the same cycle. 9 is greater than 1 and display is called with a value of n-1, which is now 8. 9 is printed out and now 8 goes through the display method. This continues to happen until the value is 1 in which case 1 is not greater than 1 and 1 is printed out and the program exits.
This is called a recursive method if you would like to look into it more.

In a recursive statment, how does java store the past values?

public class Factorial {
int factR(int n){
int result;
if(n==1)return 1;
result=factR(n-1)*n;
System.out.println("Recursion"+result);
return result;
}
I know that this method will have the output of
Recursion2
Recursion6
Recursion24
Recursion120
Recursive120
However, my question is how does java store the past values for the factorial? It also appears as if java decides to multiply the values from the bottom up. What is the process by which this occurs? It it due to how java stores memory in its stack?
http://www.programmerinterview.com/index.php/recursion/explanation-of-recursion/
The values are stored on Java's call stack. It's in reverse because of how this recursive function is defined. You're getting n, then multiplying it by the value from the same function for n-1 and so on, and so on, until it reaches 1 and just returns 1 at that level. So, for 5, it would be 5 * 4 * 3 * 2 * 1. Answer is the same regardless of the direction of multiplication.
You can see how this works by writing a program that will break the stack and give you a StackOverflowError. You cannot store infinite state on the call stack!
public class StackTest {
public static void main(String[] args) {
run(1);
}
private static void run(int index) {
System.out.println("Index: " + index);
run(++index);
}
}
It actually isn't storing 'past values' at all. It stores the state of the program in the stack, with a frame for each method call containing data such as the current line the program is on. But there is only one value for the variable result at any time, for the current method on top of the stack. That gets returned and used to compute result in the frame that called this, and so on backwards, hence the bottom up behaviour you see.
One way to make this less confusing is to take recursion out of the picture temporarily. Suppose Java did not support recursion, and methods were only allowed to call other, different methods. If you wanted to still take a similar approach, one crude way would be to copy paste the factR method into multiple distinct but similar methods, something like:
int fact1(int n){
int result;
if(n==1)return 1;
// Here's the difference: call the 'next' method
result=fact2(n-1)*n;
System.out.println("Recursion"+result);
return result;
}
Similarly define a fact2 which calls fact3 and so on, although eventually you have to stop defining new methods and just hope that the last one doesn't get called. This would be a horrible program but it should be very obvious how it works as there's nothing magical. With some thought you can realise that factR is essentially doing the same thing. Then you can see that Java doesn't 'decide' to multiply the values bottom up: the observed behaviour is the only logical possibility given your code.
well i am trying to understand you,
if someone call likewise then
factR(3) it's recursive process so obviously java uses Stack for maintaining work flow,
NOTE : please see below procedural task step by step and again note
where it get back after current task complete.
result=factR(2)*3 // again call where n=2
-> result=factR(1)*2 // again call where n=1
-> now n=1 so that it will return 1
-> result=1*2 // after return it will become 6
print "Recursion2" // print remaning stuff
return 2;
result=2*3 // after return it will become 6
print "Recursion3" // print remaning stuff
return 3

Tracing through a Binary Tree

I have the following Binary tree
3
/ \
5 2
/ \ /
1 4 6
My weekness is recursion, so please bear with me, and I need your help to trace through it to get it right.
I have the following code, and what it does is print the nodes in Post Order.
So the answer is 1 4 5 6 2 3
void Postorder(Node root) {
if(root == null){
return;
}
Postorder(root.left);
Postorder(root.right);
System.out.print(root.data + " ");
}
Lets Trace:
Root = 3 (top node), not null, Root.left(5) - go back up to the function
Root = 5, Not null, Root.left(1) - go back up to the function
Root = 1, Not null, Root.left(null), continue, Root.right(null)
Print 1
now this is where I get confused, Root = 1 at this point, I don't see how I go back up to 5 and then go to the right node in the logic. In addition, when I go back up to 5, where do I check if 1 has been visited ?
I am confused.
Thanks for your help.
Perhaps the picture will help. I find recursion difficult as well, and I've found pictures useful. It might be nice to open the diagram in a separate window and have the explanation on the side.
First of all, recursion uses something called a stack. It's the pile of four rectangles you see in the diagram. For example, there are two empty stacks at the very end. Suppose a function A() calls a function B() before A has terminated. Then what needs to happen is we execute A() partway through, then execute B(), then go back and finish executing A(). But when we go to execute B(), we need to remember where we were in A(). Thus, we need to store the information about A() and B() in individual rectangles in the stack. That way, after we finish executing B(), we know where we left off in A() and can finish the function.
So maybe it will help if we step through the recursion with the diagram of the stack. Also suppose we have this:
public static void main( String[] args ) {
Postorder(3);
}
1
So initially, main runs and its contents get added to the bottom of the stack, as we see in part 1.
1->2
But when main() calls Postorder(3), it hasn't terminated yet. So, in another stack frame, we add the contents of the Postorder(3) function call. You can see this in part 2. The yellow arrows remember where we left off in each stack frame before we went to execute another function.
2->3
Now, we're executing Postorder(3) and we reach the function call Postorder(5). But Postorder(3) hasn't finished running, so in another stack frame, we have to add the contents of Postorder(5). You can see this in part 3.
3->4
Now we're executing Postorder(5). We reach the function call Postorder(1). But Postorder(5) hasn't finished running, so in another stackframe, we have to add the contents of Postorder(1). For simplicity, since 1 has no subnodes, we'll say that Postorder(1) is equivalent to Print(1). This corresponds to part 4.
4->5
Now, in part 4, Print(1) executes, and Postorder(1) terminates. When Postorder(1) terminates, it can be removed from the stack. Also, since Postorder(1) finished, we can resume executing Postorder(5). The yellow arrow tells us that we left off at line 1 of Postorder(5) before we jumped off to execute another function. Well, we can now move on to line 2 of Postorder(5). This corresponds to part 5.
5->6
Line 2 of Postorder(5) is the command Postorder(4). Since Postorder(5) has not yet finished executing, we must add the contents of Postorder(4) to another stack frame. This corresponds to part 6.
...
It's pretty much the same idea from then on. Let me know if you still want me to step through the remaining 8 parts. It gets a bit tedious afterwards. Hopefully this visual helps.
Right, so when you're at Root 1 (a leaf) it will return to the node that called it (5).
Since at "Root 5", it just finished calling Postorder(root.left); (which just returned from printing 1), the next line will run and call Postorder(root.right); .
This will call root = 4. Not null, root.left(null), continue, root.right(null), continue, now print 4.
Now we jump back to the calling node, root = 5. Now its already called Root.left(1); and Root.right(4);. So now its going to print 5.
It will now return to the calling node - in this case the root of the entire tree, root = 3 and now it will traverse the right side in a similar manner.
The recursion is simple. All you need to do is continuously separate the Binary Search Tree into left and right sub-trees.
You also might want to consider creating getters for your variables to better encapsulate your Node class.
Postorder function
public void Postorder( Node root )
{
if( root == null )
return;
// Output the left tree.
if( root.left != null )
Postorder( root.left );
// Output the current node.
System.out.print( root.data + " " );
// Output the right tree.
if( root.right != null )
Postorder( root.right );
}
Understanding and visualizing recursion Maybye this will help you, because your understand recursion wrong. U need to remember ALL function calls.

Categories

Resources