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.
Related
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.
This question already has answers here:
Understanding recursion [closed]
(20 answers)
Closed 5 years ago.
Before you get started, I have used google countless times in hopes of searching for a very brief and simple explanation of how recursion works when it has a return type. But I guess I'm not as bright as I thought since i still cant understand it quite well.
Take the following code snippet (in java) as an example
public static int recursion(int num)
{
int result;
if (num == 1)
result = 1;
else
result = recursion(num - 1) + num;
return result;
}
I grabbed this code from my professors lecture slide and he said this will return 1 + 2 + 3 + ... + num.
I just need someone to explain how the process works in the method that i provided. Maybe a step by step approach might help me understand how recursion works.
recursion(5) = recursion(4) + 5, let's figure out recursion(4) and come back to this later
recursion(4) = recursion(3) + 4, let's figure out recursion(3) and come back to this later
recursion(3) = recursion(2) + 3, ...
recursion(2) = recursion(1) + 2, ...
recursion(1) = 1, we know this!
recursion(2) = 1 + 2, now we can evaluate this
recursion(3) = (1+2) + 3, and now we can evaluate this
recursion(4) = (1+2+3) + 4, ...
recursion(5) = (1+2+3+4) + 5, the answer to our original question
Note: Without knowing recursion(1), we'd have gone to 0, -1, -2, and so on until forever. This known quantity is called the base case and it is a requirement for recursion.
Basically when there is a stack buildup for each item that is created beyond the last iteration. (Where num=1)
When n>1 the if statement kicks the iteration to the else which 'saves' the result in a stack and calls the same funtion again with n-1
what this effectively does is keep calling the same function until you hit your designated 'base case' which is n=1
Recursion is all about solving a problem by breaking it into a smaller problem. In your case, the question is "how do you sum the numbers from 1 to n", and the answer is "sum up all the numbers from 1 to n-1, and then add n to it". You've phrased the problem in terms of a smaller or simpler version of itself. This often involves separating out a "base case"—an irreducibly simple problem with a straightforward answer.
public static int recursion(int num)
{
int result;
if (num == 1)
result = 1; // Base case: the sum of the numbers from 1 to 1 is 1.
else
result =
// This is the sum of numers from 1 to n-1. The function calls itself.
recursion(num - 1)
// Now add the final number in the list, and return your result.
+ num;
return result;
}
You're defining the unsolved problem in terms of itself, which works because the solution always involves either the base case or a simpler version of the problem (which itself further involves either the base case or an even simpler version of the problem).
I'll close with one of my favorite jokes:
How do you explain recursion to a five-year-old?
You explain recursion to a four-year-old, and wait a year.
Going by the classic code example you posted. if you call your method like so with number passed in as 5:
recursion(5);
In layman terms just to understand, your function will create & call another copy of your function in the else block as below:
recursion(4);
and then
recursion(3);
recursion(2);
recursion(1);
as the number keeps decrementing.
Finally it will call the if part in the final copy of the method as num will satisfy num == 1. So from there it starts unwinding & returning each value to the previous call.
As each method call has its own stack to load method local variables on, there will be n number of stacks created for n calls. When the deepest call in recursion is made, then the stacks start unwinding. Hence recursion achieved
The most important thing however to note is that there is a base-most call in your code, which is done at 1 just because you have the check if (num == 1). Else it would be infinite recursion & of course a fatal & wrong program to write. The base-most call is from where its called as stack unwinding in recursion terms.
Example: Finding the factorial of a number is the most classic examples of recursion.
Performance: Do look into recursion vs iteration and recursion vs looping to see what are the performance impacts of recursion
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.
I have just started taking a Computer Science class online and I am quite new to Programming(a couple of week's worth of experience). I am working on an assignment, but I do not understand what a mystery method is. I have yet to find an answer that I can wrap my head around online, in my textbook, or from my professor. Any explanation using this code as an example would also be greatly appreciated!
This is the equation where I saw it in:
public static void mystery1(int n) {
System.out.print(n + " ");
if (n > 0) {
n = n - 5;
}
if (n < 0) {
n = n + 7;
} else {
n = n * 2;
}
System.out.println(n);
}
If anybody can help, that would be amazing! Thank you!
First of all, I voted your question up because I think it's a valid question for someone who is just beginning in computer programming, and I think that some people fail to understand the significance and purpose of Stack Overflow, which is to help programmers in times of need.
Secondly, I think that the couple of users that have commented on your post are on the right track. I have personally never heard of a mystery method, so I think the goal here is for you to simply figure out what the method does. In this case, the method takes a parameter for int 'n'. This means that if, at any point in the application, the 'mystery1()' method is called, an integer will have to be passed as the variable.
Let's say that a user enters the number '9'. The method would be called by the code mystery1(9). This would then run the first part of the 'if' statement, because n is greater than 0. So, n would be equal to n - 5, or 9 - 5, which is 4. (So, n=4.)
I hope my answer was somewhat helpful to you. Take care.
Your assignment is probably to figure out what this method does. More specifically, what does it print to the screen. I'll walk you through how to figure this out.
You have a function, also called a methood, called mystery1. A function is just a named block of code that you can use throughout other pieces of code. This function takes an integer argument called n. Let's assume n=12 for this example.
The first thing that happens in your function when it is called is that n is printed out via the System.out.print method. Notice that it prints a blank space after it. Notice also at the end it prints another value of n that gets assigned within the method. So the method is going to print "12 ?" without the double quotes. The question mark is what we have to figure out. The code says if n > 0 then n = n-5. Since 12 is greater than 0, n gets the new value of 7. The next if statement says if n is less than 0, n gets assigned n+7. But it is not less than zero, it is 7 at this point, so we move to the else statement. In this statement n gets multiplied by 2 which is 14. So the last statement prints 14.
So for an input value of 12 this method prints:
12 14
I hope this helps. If not, please give more detail about your assignment and what you don't understand about my explanation.
The point of this kind of exercise is that you are given a method, but they don't tell you what it does (hence the "mystery"). You are supposed to figure out what it does on your own (like "solving the mystery"). It doesn't mean that the method is special in any way.
Say I give you a "mystery" method like this:
public static void mystery(int n) {
System.out.println(n+1);
}
You would "solve the mystery" by telling me that this method prints out the number that comes after n. Nothing else is special here.
In the example you gave, your job would be to tell me why the method prints out 0 0 when n = 0, or 6 2 when n = 6.
I think the usage of the term "mystery method" is rather misleading, as it has clearly made you (and many, many, many others) believe that something about these methods is special and something that you need to learn about. There isn't anything special about them, and there's nothing to learn.
I think a lot of people would understand this better if instructors just said "tell me what this method does" instead of trying treat students like 5 year olds by saying "Here's a mystery method (ooh, fancy and entertaining). Can you play detective and solve the mystery for me?"