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.
Related
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.
I'm not understanding this code, why it counts up. If I change the order in the print statement with recursivity call It makes sense to me, but as it is why it is counting up. In by book it says that "System.out.println happens just before each recursive call returns. As a result, it counts up instead of down." And I am not understanding It. Appreciate your help.
public static void countdown(int n)
{
if (n == 0)
{
System.out.println("Blastoff!");
}
else
{
countdown(n - 1);
System.out.println(n);
}
}
So, if n != 0, your program running code in "else" block, where is another call to method countdown(n-1). For example, if you put n = 3, this code will be running as long as n > 0. So, basiclly running method run herself, looks like this:
countdown(3) call method countdown(2), and then countdown(2) call countdown(1). It will happen as long as n will be higher than 0. If n == 0, it will print Your message.
you should change the condition 'n == 0' to 'n <=0'. because if you pass negative value then it wont stop and you might see negative number.
lets says if you passed n = -3. then it would keep printing -3, -4...etc.
countdown(n - 1);
System.out.println(n);
It indeed counts up.
Let's take a look at what actually happens: Each countdown call first calls itself, even before anything is written to System.out.
In the following example, let's say I call countdown with 2 as argument.
countdown(2) is called
within this method call, n == 2, so else block is executed
countdown(1) is called
within this method call, n == 1, so else block is executed
countdown(0) is called
within this method call, n == 0 thus the if-condition is true, so "Blastoff!" is printed
this method exits, returning to the method denoted by step 3.
n is printed, which has the value 1.
the method exits, returning to the method denoted by step 1.
n is printed, which has the value 2.
the method exits
Note that each method call has its own local variables, like n. So the output is:
Blastoff!
1
2
as expected. You see that, just according to what the book says, the method calls itself prior to printing something to sysout.
This question already has answers here:
Recursive Method Prints 4 Times
(4 answers)
Closed 5 years ago.
I want to ask exactly what happens with the code after the recursion line ?
Here is sample code :
public static void method(int index){
--index;
if (index < 0) {
return;
}
method( index);
System.out.println(index);
}
My question is why sout prints my number in reverse order when it is after the recursion line : 0 1 2 3 4
Thanks in advance.
Before each print you call method(number-1)
When reach -1 you start calling the recursion stack from 0 until your number index
The stack is piling and we keep popping the last one from stack:
0
1
...
number-1
number
Your application is single thread, so all instructions are executed one after one.
Once you call a method next line is called after method completes.
Your execution of method(4) is as it follows:
method(4)
method(3)
method(2)
method(1)
method(0)
method(-1)
- here, there is no more recursion call - method returns before calling method another time. Look, it returns, so we fall back to method(0) execution - print 0 is executed. Then we return and finish method(1):
print 0
print 1
print 2
print 3
print 4
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
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.