This question already has an answer here:
Recursive function : print statement before/after function call
(1 answer)
Closed 11 months ago.
I can't seem to figure out why this recursion program prints the values the way it does. I thought it would print [9]9 first but intead it does it backwards from [0]0. Can anyone explain why this happens?
class RecTest {
int values[];
RecTest (int i){
values = new int[i];
}
void printArray(int i) {
if(i==0) return;
else printArray(i-1);
System.out.println("[" + (i-1) + "]" + values[i-1]);
}
}
public class Recursion2 {
public static void main(String[] args) {
RecTest ob = new RecTest (10);
int i;
for(i=0; i<10; i++) ob.values[i] = i;
ob.printArray(10);
}
}
The printArray method works by calling itself decreasing the integer i. The System.out.println statement is executed after calling the function with i-1. For example, given an input of 10:
printArray(10) is exectued -> printArray(10-1) is called
printArray(9) is executed -> printArray(9-1) is called
[...]
printArray(0) is executed -> return. The program goes back to the previous istance of printArray, the one where i = 1
We are here in the code: the line printArray(1-1) has just been executed. The next line is System.out.println("[" + (1-1) + "]" + values[1-1]) -> [0]0 is printed (right now i = 1). Now the program goes back to the previous instance where i = 2
[...]
I think you can figure out the rest :)
See if this helps.
static void printVal(int i) {
if (i > 0) {
System.out.printf("Calling printVal(%d) again%n", i-1);
printVal(i-1);
}
System.out.println("Returning from print - call stack has " + i);
}
printVal(10);
prints
Calling printVal(9) again
Calling printVal(8) again
Calling printVal(7) again
Calling printVal(6) again
Calling printVal(5) again
Calling printVal(4) again
Calling printVal(3) again
Calling printVal(2) again
Calling printVal(1) again
Calling printVal(0) again
Returning from print - call stack has 0
Returning from print - call stack has 1
Returning from print - call stack has 2
Returning from print - call stack has 3
Returning from print - call stack has 4
Returning from print - call stack has 5
Returning from print - call stack has 6
Returning from print - call stack has 7
Returning from print - call stack has 8
Returning from print - call stack has 9
Returning from print - call stack has 10
Each subsequent call to printVal puts the value-1 on the call stack. When they are all finally returned, they return in the reverse order.
Related
public class Test{
public static int sum(int num){
if (num <= 1){
return num;
}
return 2 + sum(num -1);
}
public static void main(String []args){
System.out.print(sum(7));
}
}
I'm trying to understand recursion? Why is it when I run this code the answer is 13?
Follow it by hand on paper. The first thing that happens is sum(7). That call checks for num <= 1, which is false. So, in order to do the next line, it has to call sum(6). The original call is pushed on the stack, and we start handling sum(6). That call also falls through the if, and calls sum(5).
Eventually we are nested 7 levels deep:
sum(7)
sum(6)
sum(5)
sum(4)
sum(3)
sum(2)
sum(1)
Now, in the sum(1) call, num is <= 1, so we return 1. They key is, where do we return? We return out one level, to the call for sum(2). Its call to sum(1) returned 1. We add 2 to that and return 3.
Now, we're in the sum(3) call. It got 3, so it returns 5.
Now, we're in the sum(4) call. It got 5, so it returns 7.
And so on. Eventually, we get to the outer sum(7) call. Its call to sum(6) returned 11; it adds 2 and returns 13.
The main function gets 13.
sum(1) is 1.
sum(2) is 2 + sum(1), so it's 3.
sum(3) is 2 + sum(2), so it's 5.
sum(4) is 2 + sum(3), so it's 7.
sum(5) is 2 + sum(4), so it's 9.
sum(6) is 2 + sum(5), so it's 11.
sum(7) is 2 + sum(6), so it's 13.
public class GetElementWithoutPop {
public static void main(String args[]) {
Stack<Integer> stack = new Stack<Integer>();
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.push(50);
stack.push(60);
System.out.println("value is: " + GetElementWithoutPop.getStackElement(stack, 3));
System.out.println("stack is " + stack);
// Using Java
int position = 3;
Integer result = stack.get(position);
System.out.println(result);
}
public static <T> T getStackElement(Stack<T> stack, int index) {
if (index == 0) {
return stack.peek();
}
T x = stack.pop();
try {
return getStackElement(stack, index - 1);
} finally {
stack.push(x);
}
}
}
Till the index becomes 0 from 3 it's all good and simple, but after that the code goes back to try block and then again to finally block and the index starts to increase on its own all the way back to 3 and stack.push(x) brings the stack back to its original state.
How is this happening?
Fairly new to recursions & I need to understand this!
This happens because each function call has its own unique context for the same function so the variable x stores the popped variable and calls recursively to pop further value but that value is stored in x of the next function call, while returning the finally block runs and each unique value of x in each function call is again pushed
T x = stack.pop(); // this value remains stored in the function call stack
try {
return getStackElement(stack, index - 1); // same function runs for further case (n-1) th and stores the value in its own x variable in its context
} finally {
stack.push(x); // after the control returns, this copy of function has its unique x variable and that is pushed again
}
You mention that "index starts to increase on its own all the way back to 3 .." that's because each function call has its own set of variables including index
Some Steps
1) Function call instance with index 3 calls function with index 2
2) Function call instance with index 2 calls function with index 1
3) Function call instance with index 1 calls function with index 0
4) Control returns
5) Now the control is back to instance with index value 1
6) Control returns from even that instance and now is back to instance with index 2
This is like winding and then unwinding,, while solving problems with recursion we have to often decide whether we want to do some work at call for n and then call for n-1 OR call for n-1 , let the control return and then do some work
I have been trying to figure out why the output is 321 and not 123. I have tried multiple times and looking out lecture slides but I still can't get the solution to this question.
public static void main(String[] args) {
printNumber(1);
}
public static void printNumber(int n) {
if(n!=4) {
printNumber(n + 1);
System.out.print(n);
}
}
Each call to printNumber calls printNumber(n+1) first, and then prints something out. So printNumber(n+1) has already finished before printNumber(n) prints its number out.
main():
printNumber(1):
printNumber(2):
printNumber(3):
printNumber(4) // does nothing
print(n) // "3"
// printNumber(3) completes, returning control to printNumber(2)
print(n) // "2"
// printNumber(2) completes, returning control to printNumber(1)
print(n) // "1"
// printNumber(1) completes, returning control to main()
// main() completes
The variable n is either 1 2 or 3.
What are you printing first, n or n + 1? You are printing n + 1 first, then n. So the numbers must come out in reverse order.
The reason for this result that you have placed the recursion call statement printNumber(n + 1)
before print statement System.out.print(n) so it will keep recursivly calling it until it reach 4 after that it will print numbers from last call n+1 to n as in our example from 3 to 1
try this :
public static void printNumber(int n) {
if(n!=4) {
System.out.print(n);
printNumber(n + 1);
}
}
you will find the output: 123
The reason for that is at each recursion call it will print the number n then it will call it another time for n+1 until it reach 4.
i am trying to print numbers from 1 to 10 without using loops in java. When n+1 is passed to recursivefun method call in line 6,it works fine. But when n++ is passed,the code throws an error :/
public class PrintWithoutUsingLoops {
public static void recursivefun(int n) {
if (n <= 10) {
System.out.println(n);
recursivefun(n++);//an exception is thrown at this line.
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
recursivefun(1);
}
}
recursivefun(n++);
passes the original value of n to the recursive call (since you are using the post-increment operator), making this recursion infinite (since each recursive call gets the same value of n, which never reaches 11) and leading to StackOverflowError.
Change it to
recursivefun(n+1);
or
recursivefun(++n);
recursivefun(n++);
is a call with post-increment. Post increment is a mechanism which enlarges the value after it is read. In this case, you always pass 1.
You can use pre-increment which is ++n which first: increments and then passes the value.
The exception you get is StackOverflowError which means, that the stack is full and JVM cannot store more calls on stack, so it won't be able to revert.
recursivefun(n++);
This line means : call recursivefun(n); and then increment n by 1 so you'll always call your fuction with n=1 and caused a stackOverflow sure
So you need to increment n BEFORE all the function, you have some options :
recursivefun(n+1);
//-----------------------------
n++;
recursivefun(n);
//-----------------------------
recursivefun(++n); //pre-cincrement
Indeed both post and pre increment operators increments the value of a variable. Their behavior changes based on the context of the usage. Assume the following code:
For loop 1:
for (i=0; i<10; i++)
...
For loop 2:
for (i=0; i<10; ++i)
...
In both of the above statements, the for loop iterates 10 times irrespective of the increment style used. However consider the following code:
int x = 10;
int y = 20;
int z = x++ + ++y; // z = 10 + 21
System.out.println("x = " + x); // prints 11
System.out.println("y = " + y); // prints 21
System.out.println("z = " + z); // prints 31
Hence from your code it is evident that
recursivefun(n++);
calls recursivefun with argument 1 infinitely. To avoid StackOverFlow error use either ++n or n+1.
I'm new to java programming, and our teacher taught us the concept of recursion and I found it to be a bit complicated. All I understood that it works like a loop(like the factorial of 4) but I still don't quite get it why it works like that. Can I get a detailed explanation on this topic? Here is the piece of code and a picture my teacher used to explain.
package javaapplication1;
public class JavaApplication1 {
static int factorial(int n){
int t;
if(n == 0){
return 1;
} else {
t = factorial(n - 1);
return n * t;
}
}
public static void main(String[] args) {
System.out.println(factorial(5));
}
}
In the following image, the blue color represents stack winding, and the green is stack unwinding, and again I don't know what stack winding and unwinding is.
http://i.stack.imgur.com/pjqJy.png
A recursive function is a function that calls itself until it reaches a return statement, that stops it from recalling itself. Take your example, the Factorial function.
Factorial is a mathematical function that returns the number multiplied by itself - 1 multiplied by itself - 2, ... multiplied by 1, example: factorial of 5 = 5! = 5x4x3x2x1 = 120.
it is also equal to itself multiplied by the factorial of itself -1, which is: 5! = 5x4!
Take into consideration that 0! = 1.
to represent this in a Java code, you need a loop that multiplies the numbers starting from 1, and going till the number you are calculating its factorial.
Further more, explaining your code, let us calculate Factorial(5):
Factorial() returns an integer.
Initial Call from main(): 5 != 0, then skip the condition (n == 0); t
= Factorial(5-1) = Factorial(4);
Second call from Factorial(4): 4 != 0, then skip the condition (n ==
0); t = Factorial(4-1) = Factorial(3);
Third call from Factorial(3): 3 != 0, then skip the condition (n ==
0); t = Factorial(3-1) = Factorial(2);
Fourth call from Factorial(2): 2 != 0, then skip the condition (n ==
0); t = Factorial(2-1) = Factorial(1);
Fifth call from Factorial(1): 1 != 0, then skip the condition (n ==
0); t = Factorial(1-1) = Factorial(0);
Sixth call from Factorial(0): 0 == 0, then return value 1;
First return, 1, to Fifth call (Factorial(1)): return n*t = return 1*1
= return value 1;
Second return, 1, to Fourth call (Factorial(2)): return n*t = return
2*1 = return value 2;
Third return, 2, to third call (Factorial(3)): return n*t = return 3*2
= return value 6;
Second return, 6, to second call (Factorial(4)): return n*t = return
4*6 = return value 24;
Second return, 24, to First call (Factorial(5)): return n*t = return
5*24 = return value 120;
Second return, 120, to Initial call (from main()): print(120);
Hope this helps you understand recursion.
When a call is made to another method, a stack frame is created to hold the state of the current method and it is pushed onto the stack. This is regardless of a method calling itself or another method.
When the call returns, the stack frame is popped of the stack, the state of the method is restored and execution continues in the calling method.
Recursion is when a method (directly or indirectly) calls itself. The general form of a recursive method is:
If a parameter meets a terminating condition, return (usually a result)
Else adjust parameters for the next iteration and call self
The code your teacher wrote has some style issues. It would be clearer if written like this:
static int factorial(int n) {
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}
Eradicating the unnecessary variable t and redundant else (there is no "else" when the "if" returns - there is merely continuation of execution)
I would write it like this, eliminating the if altogether:
static int factorial(int n) {
return n == 0 ? 1 : n * factorial(n - 1);
}
When one knows that a task can be broken into similar smaller tasks ,then we use recursion or calling the same method(until we met a certain condition).Recursion not only helps in execution of a problem without having to define or invoke another method,it also helps in visualizing a pattern by which the task is getting executed
Personally, I do not like the factorial problem. I find it hard to understand and I do not think it explains recursion in a clear way. So lets look at a different example. Lets say that we want to print numbers from 1-100. This is a very simple task with a for loop and a counter, but it can also be done with recursion. For example:
public static void main(String[] args) {
numbersAscending(1);
numbersDescending(1);
}
//Prints 1 2 3 ... 100
public void numbersAscending(int x){
System.out.println(x);
if(x < 100){
numbersAscending(x+1);
}
}
//Prints 100 99 98 ... 1
public void numbersDescending(int x){
if(x < 100){
numbersDescending(x+1);
}
System.out.println(x);
}
When a function is called, that call goes on top of the stack. Think of this like a stack of cards. Each one has a number on it (1-100). When a function calls itself, a new card gets added to the stack. When the function finishes, it is taken off of the stack.
So for the example above, every time numbersAscending is called, it prints out the current value for x before calling that function again. This results in the numbers being printed in order from 1-100. As soon as 100 is reached, it stops calling itself and pops each function off of the stack.
On the other hand, every time numbersDescending is called, it calls itself again before printing out the number. In this way, x doesn't start printing until it reaches 100. It then moves back down the stack, printing each number as it goes back to the main method.
/*This program in java will help you to understand all the basics of
recursion:
->how control flows in recursion
->how return is executed in the recursive functions
->how and when the statements after recursive function area executed.*/
public class Understanding_Rec{
public static int rec(int x)
{
if(x<5)
{
System.out.println("-->Smaller than 5");
rec(x+1);
System.out.println("<--After recursion inside x<5");
return x;
}
else if(x<7)
{
System.out.println("-->Smaller than 7");
rec(x+1);
System.out.println("<--After recursion inside x<7");
}
System.out.println("<--No Condition Statement");
return x;
}
public static void main(String[] args)
{
int x=1;
rec(x);
System.out.print(x+"Inside main");
}
}
I am not sure if it explains, but if you had a precalculus class then you should know that factorial can be defined in two waqys.
n!=1*2*...*n
of we define
1!=1
and
n!=n*(n-1)!
Try to see yourself that those definitions are equivalent. Pick let us say, 5!
according to second definition
5!=5*4!
but 4!=4*3! so 5!=5*4*3!
but 3!=3*2! so 5!=5*4*3*2!
and so on. Keep doing it until you hit 1!. But 1!=1 so you stop.
Recursion in programming is the same thing.
TomW