Printing Recursively - java

I have this class the just prints an int:
class PRecursion {
public static void main(String[] args){
foo(1);
}
public static void foo(int x){
System.out.println("" + x);
if (x < 3)
foo(x+1);
System.out.println(""+x);
}
}
Output:
1
2
3
3
2
1
Why is it the is printing backwards then decrements?

It is not actually decrementing. What is happening is:
You are calling foo(1).
foo(1) does it's thing and starts a recursion.
Recursion goes on for how long you tell it to (foo(3) in your example)
After the recursion is done, foo(1) still has one statement to execute, and that is:
System.out.println(""+x);
hence you are seeing the print of foo(1) a second time, but after all other prints have been made. The same goes for every other time foo() is being called with a different number. So in the end it looks like it is decrementing, when really you are only printing a second time for the same value, in reverse order.

Try this:
class PRecursion {
public static void main(String[] args){
foo(1);
}
public static void foo(int x){
System.out.println("before " + x);
if (x < 3)
foo(x+1);
System.out.println("after "+x);
}
}
The second print statement doesn't decrement the input. What is happening is it leaves the call of foo(3) before it leaves the call of foo(2) and then finally `foo(1). So it executes the second print statements in the reverse of the order of the first.
If you read out the execution of the program as:
set x=1
print x (i.e. 1)
push x=1 on stack and set x=2 (this is how you can read foo(x+1))
print x (i.e. 2)
push 2 on stack and set x=3
print x (i.e. 3)
Don't push anything (x<3 is false)
print x again (i.e. 3)
pop x=2 off the stack
print x (i.e. 2)
pop x=1 of the stack
print x (i.e. 1)
stripping out the pushing and popping you get:
print 1
print 2
print 3
print 3
print 2
print 1

The value of x is not decrementing but it executes the remaining part of code which looks like decrementing.
System.out.println(" " + x); // 1 2 3
if (x < 3)
foo(x+1);
System.out.println(""+x); //3 2 1
due to recursion it calls the same function again and again and print only the first print statement until the if condition is true but at the end when if is false it stop executing foo(x+1) and exute the remaining print statements as the execution in the last step x is 3 so it prints 3 2 1 .
Maybe this could clear a bit more
Since all the foo(1)-->foo(2)-->foo(3) is executed causing output 1 2 3 the execution is in the last method foo(3) so it started executing the remaining method statement with flow like foo(3)-->foo(2)-->foo(1) printing the remaining print statement which executes looks like all the function backwards resulting in remaining 3 2 1.

Related

In this example of recursion, how come the second printline prints the second half of the output?

I understand how calling the recursion method (n-1) prints out 4 3 2 1, and since on the last one, n=0; it breaks out of the loop I think, however, my lack of understanding comes from how the second print line prints 1 2 3 4.
static void recursion(int n) {
if(n>0) {
System.out.println(n);
recursion(n-1);
System.out.println(n);
}
}
public static void main(String[] args) {
recursion(4);
}
}
output:
4
3
2
1
1
2
3
4
You call recursion(4)
which prints 4
then calls recursion(3)
which prints 3
then calls recursion(2)
which prints 2
then calls recursion(1)
which prints 1
then calls recursion(0)
which does nothing
and returns to the previous level
which prints 1
and returns to the previous level
which prints 2
and returns to the previous level
which prints 3
and returns to the previous level
which prints 4
and returns to the previous level
and we're done

Java method executes last print statement three times even though the method is only called once

I'm trying to figure out why this mystery method in Java prints out "43211234". I understand how the program reaches "43211" but I'm not sure how the last System.out.print(x % 10) after the "if" is ran 3 times and for each time, it brings the value of x back to the value it was previous to its current one until it reaches "1234" as the value of x. Could this have something to do with recursion since the method is being called in the "if" 3 times? I'm guessing it's something along those lines because the last executes exactly 3 times as well. I would greatly appreciate your help. Thanks.
class Main {
public static void main(String[] args) {
mystery(1234);
}
public static void mystery(int x) {
System.out.print(x % 10);
if((x / 10) != 0) {
mystery(x / 10);
}
System.out.print(x % 10);
}
}
Not sure if my answer will be any more useful than the previous ones, but I'll try. So, basically, your program uses 2 types of recursion: backward recursion and forward recursion. My answer here is not to describe them to you, but to give you a starting point for more information on them.
Let's trace your program's execution:
mystery(1234) -> print(4) -> mystery(123); At this point, the System.out.print(x % 10); at the end of the method has not been called yet since your program has gone further in the recursion. It will be executed once the program returns from deep inside your recursion, and will be executed with whatever's left.
mystery(1234):
print(4);
mystery(123):
print(3);
mystery(12):
print(2);
mystery(1);
print(1);
print(1); //This is the first System.out.print(x % 10); from the end of the method, that is executed
print(2);
print(3);
print(4);
I understand how the program reaches "43211"
so you know what recursion is.
Everytime mystery() is called, the 1st print is called and then it calls (recursively) itself, before the 2nd print.
When the recursion stops because (x / 10) != 0 is false, the 2nd print is called for the 1st time and then goes back to the previous unfinished recursive calls and executes the remaining print for each one.
Your mystery() method does the following:
print the final digit of the input number (num % 10 gives the last digit)
make a recursive call mystery(x / 10), assuming x / 10 is not zero
then on the way out from the recursion, print the final digit of the input again
Putting this together, with an input of 1234, it means we would print those digits in reverse, then print them again in order.
If this answer still leaves you with doubts, I suggest running your code, beginning with a two digit input like 12, until it is clear what is happening.
This is your recursion stack. This is perfectly fine.
mystery(x / 10); input 1234 prints 4
-> mystery(x / 10); input 123 prints 3
-> mystery(x / 10); input 12 prints 2
-> mystery(x / 10); input 1 prints 1
Just make sure your remove the second sysout that you that you in your code. That is the reason it is printing the same numbers in again.

Integer powers program Java help needed

So i was getting this program in my book and tested it, it worked fine. I need help though understanding how it excactly works. I know the power of two means for example 2x2x2x2x2x2x2x2x2 = 512. Well, here is the program:
// Compute integer powers of 2.
class Power {
public static void main(String args[]) {
int e;
int result;
for(int i=0; i < 10; i++) {
result = 1;
e = i;
while(e > 0) {
result *= 2;
e--;
}
System.out.println("2 to the " + i + " power is " + result);
}
}
}
So i've learned that result *=2 means: result = result * 2. I don't get how this works. Example, i is now 4. Result = 1 again, e=i, so e is now 4. 4 is higher than 0, so the while loop runs. Then it say's result is result * 2, but that's 1=1 * 2 = 2. But the result should be 16. How does result changes here to 16? Because it is 1 all the time. I don't get it. Also, why the e-- part? I've tried the program with e++, but then it prints result as 1 and after this only 0. Also tried it without e-- or e++ at all, but then it freezes in the dos-prompt. Please note that i am a beginner and this is my first while loop. Any help i would appreciate.
while(e > 0) {
result * = 2;
e--;
}
this loop executes untill the e becomes zero.
so in first loop
result = 1 * 2;
in second loop
result = result * 2; means result = 2 * 2
likewise.
You are using nested loops. That is, a while loop inside a for loop. This means that for every iteration of for loop, while loop will execute until it's condition becomes false.
Now coming to your questions, for first iteration of for, i = 0. Which means that e = 0, which in-turn means that while loop will not execute. So, result is 1 here, which is logical since any n^0 = 1.
For second iteration of for, i = 1. Which means that e = 1. Here, while loop will run for 1 iteration. It will make result = 2 (result *= 2). So, result is 2 because 2^1 = 2.
Below is the dry-run table.
for i while e result
loop loop
1 0 1 0 1
2 1 1 1 2
3 2 1 2 2
1 2 1 4
4 3 1 3 2
2 2 2 4
1 3 1 8
and so on. This table seems ugly, but it will give you a hint.
How does result changes here to 16? Because it is 1 all the time.
Result is only initialized with 1, but it's value is multiplied each time while loop executes.
I've tried the program with e++, but then it prints result as 1 and
after this only 0.
If you put e++ instead of e--, this loop will run until e overflows. But as soon value of e reaches 33, result will become 0 due to multiplication. And after that, it will remain 0.
Also tried it without e-- or e++ at all, but then it freezes in the
dos-prompt.
It means that your condition of while loop will never become false, and hence, it will be an infinite loop.

Trouble understanding output from a recursive function.

I'm having trouble understanding what happens to this piece of code when it returns. After it outputs 10 9 8 7 6 5 4 3 2 1 0 why does it outputs 1 after 0 and not 0 again?
public static void a(int b){
if(b<0)
return;
System.out.println(b);
a(b-1);
a(b+1);
}
Well you have a(b+1) that means there is no end condition for this case which means StackOverflow. as pointed out in the comment, it is stuck between 0 and 1
If b is less than 0, the execution of the method stops. The Code below the return statement will not be executed.
While this particular example returns a StackOverflowError I don't think that's the kind of answer you're looking for. So pretending that error-causing line wasn't there let me demonstrate what is happening:
public static void a(int b){
if(b<0)
return;
System.out.println(b);
a(b-1);
a(b+1); //assuming this didn't go to infinity
}
The method runs exactly like it reads, but you create sub-tasks.
It checks the if statement, then prints the value of b. Then it runs a(b-1) and then runs a(b+1).
You're getting odd results because then it runs a(b-1) is actually a series of tasks in and of itself. THAT method does all the things I mentioned before and they will all happen BEFORE the first instance ever reaches a(b+1).
Lets say you called a(1);
1 is not less than 0
print 1
a(1-1) //which is zero a(0)
//begin sub-task a(0)
0 is not less than 0
print 0
a(0-1) // which is -1
//begin sub-task a(-1)
-1 is less than 0 so return
a(0+1)
1 is not less than zero
print 1
a(1-1) // which is zero
zero is not less than zero
print zero
a(0-1)
etc. etc.
It may be easier to think of this as
public static void a(int b){
if(b<0)
return;
System.out.println(b);
a(b-1);
System.out.println(b + " is done");
}
This does the following with a(1);:
if(1 < 0) // false
print 1
begin a(1-1) or a(0)
if(0 < 0) // false
print 0
begin a(0-1) or a(-1)
if(-1 < 0) //true so return IE go back to the calling method
print "0 is done"
print "1 is done"
A stack overflow. The call to a(b+1) every time means there will never be a point where the original function can return, or the call to a(b+1), or the call to a(b+1+1) and so on.
The return in this case just finishes the current function/method call, popping things out of the stack and going back up to the previous method call. In other words, that's just your (incomplete) base case. Unless you add a termination condition for the case where b increases, the current base case won't be enough to say stop all recursion and you'll get a SO exception.

understanding a simple recursion method

I'm starting to learn about recursion and how it can be used to solve problems.
The question is, what does the method call recur(4) display?
public static void recur (int n)
{
if(n==1)
{
System.out.print(n);
}
else
{
System.out.print(n);
recur(n - 1);
}
}
since n does not equal 1, it resorts to recur(n - 1) but this is where I am confused as to what happens here? Would the output be something along the lines of 3,2,1,0?
It will print: 4321.
If you call recur(4), then n == 4 when you start. It is not 1, so it goes to the else block, where it prints a 4, and then calls recur(3) (4-1 = 3). After that, it still isn't 1, so once again you go to the else block. This time n == 3, so 3 is printed out. Then recur(2) is called, which once again goes to the else block, printing out 2 and calling recur(1). n is equal to 1 now, so the if block is executed, which simply prints 1.
Note that you get 4321 as you have a System.out.print() statement, with no spaces. A println() would put it on a new line everytime, and you'd get:
4
3
2
1
But with a print() statement and no spacing, you'll simply get 4321

Categories