Please explain ths recursion step by step [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Please explain ths recursion step by step;
public class TestClass {
private static void printit(int i) {
if (i == 1) {
return;
}
System.out.println(i);
printit(i / 2);
printit(i / 2);
}
public static void main(String args[]) {
int i = 8;
printit(i);
}
}

If you're using IDE you can just use the debugger and see with you own eyes what's happening step by step.
Anyway, let's try and what happens when we call the recursive method:
You call the method with 8 (printit(8);):
System.out.println(8); -> 8
printit(8 /2 ); -> Call to method again with 8/2=4
System.out.println(4); -> 4
printit(4 /2 ); > Call to method again with 4/2=2
System.out.println(2); -> 2
printit(2 /2 ); > Call to method again with 2/2=1
return; -> Continues with previous call, the (printit(4 /2);)
printit(2 /2 ); > Call to method again with 2/2=1
return; -> Continues with previous call, the (printit(4 /2);)
method finishes, continues with the previous call (printit(8 /2);)
printit(4 /2 ); > Call to method again with 4/2=2
System.out.println(2); -> 2
calls printit(2/2); which we already know result in nothing.
Now we are in the first call again, the printit(8);, calling for printit(8/2);
System.out.println(4); -> 4
16 etc...

Related

Why does the output change in a recursive method? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have created a simple recursive method like this:
public void rec(int a) {
if(a > 0) {
rec(a - 1);
System.out.println(a);
}
}
the output for this method is:
1
2
3
4
5
And that's just great but the question is why when I write the print command outside the if statement the output starts from 0 not 1?
public void rec(int a) {
if(a > 0) {
rec(a - 1);
}
System.out.println(a);
}
why when I write the print command outside the if statement the output starts from 0 not 1?
Because, in the first version, the if (a > 0) prevents the function from printing 0. How about we look at what is happening here by including both prints:
public void rec ( int a) {
if(a>0) {
rec(a-1);
System.out.println("Inside if: " + a);
}
System.out.println("After if: " + a);
}
In the code
public void rec(int a) {
if(a > 0) {
rec(a - 1);
System.out.println(a);
}
}
you recursively invoke the method rec() with "a" as the parameter value for the first method invocation and then "a-1" for all the subsequent method invocations.
The rec() method has if clause which only executes if the value of parameter "a" received is greater than 0.
if the value of "a" is 0 then the method simply does nothing and returns back to invoking point and prints the value of variable a in that method scope.
An important point is that the value of "a" in a method scope is not being altered only the parameter to the next method call is being altered (i.e a-1)
Let' say the initial method call is something like
rec(5) // <-- method invoked with a = 5
//method definition
public void rec(int a) { // <-- a = 5
if(a > 0) { // 5 > 0 ? True
rec(a - 1); // rec(5-1) ie rec(4) but a = 5 still
System.out.println(a); // <-- a = 5 in this method scope
}
}
To have a better idea you can read on scopes,methods and call Stacks.
This will give a better grasp on recursion as well.

Why is the non-zero return int acting as 0? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I was tracing this and always found the last answer to be 103 but when I run the program, it's 13. The return value is not getting added to t.sum in methodThree.
I've tried modifying the line to
t.sum += methodTwo() + 7;
But the answer is the same. The value of t.sum is 12 before and after executing this line. Why is the value of t.sum unchanged in this line?
class Test {
int x = 2;
int y = 4;
int sum = 6;
Test t;
void methodOne() {
t = new Test();
t.sum += sum;
System.out.println(t.sum);
}
int methodTwo() {
System.out.println(++x);
methodOne();
System.out.println(y++);
return x * y * sum;
}
int methodThree() {
t.sum += methodTwo();
System.out.println(++t.sum);
return --sum;
}
public static void main(String[] args) {
Test t = new Test();
t.methodOne();
Test t2 = new Test();
t2.methodOne();
t2.methodThree();
}
}
I agree that it’s tricky. What teases in methodThree is that t is changed in the course of the call to methodTwo. So when you are looking at t.sum before and after that call, you are not looking at the same t. How is t changed? This happens when methodTwo calls methodOne, which in turn creates a new Test object and assigns it to t.
We also need to be aware of what the usual left-to-right evaluation means in this case. t.sum += methodTwo(); is in some sense evaluated left to right, in another sense right to left. What do I mean? Java starts from the left, looks at t.sum and from this decides which sum to add the method result to: the sum in the object that t refers to prior to the call. The call returns 90, which is added into the old t object. As I said, in the meantime a new t object has been created with a sum of 12. Therefore t.sum is also 12 after the statement has completed.

Why this recursive method is considered a factorial? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I understand everything this method does up until m=1 and n=1. What happens after if() when m=1 and n=1 is problematic.
public class exc {
public static void main(String[] args) {
System.out.println(prod(1, 4));
}
public static int prod(int m, int n) {
if (m == n) {
return n;
} else {
int recurse = prod(m, n - 1);
int result = n * recurse; // how n gets its value here?
return result;
}
}
}
What is the value of recurse? I mean how prod yields only one
integer? (since it has two integers)
In if, when m=1 and n=1 return value is 1 so why the program doesn't terminate at there? And instead it terminates after "return result;" in else?
After m=1 and n=1, n is 2 (in recurse) ; how is n set to 2? Is it because 2 is still in memory and had to be dealt with?
I checked this page
I also used println after different lines to see the out put, but that didn't help either. I also used a debugger.
Your program return the factorial when m = 1.
Take this example: (m=1, n=4)
4 != 1 -> so you call recursively prod(1, 3)
3 != 1 -> so you call recursively prod(1, 2)
2 != 1 -> so you call recursively prod(1, 1)
1 == 1 -> you return 1 to the last call
In this call, recurse = 1 and n = 2 so you return 2 to the upper call
Here, recurse = 2, n = 3, so you return 6 to the upper call
Here, recurse = 6, n = 4, so you return 24 to the upper call
END OF FUNCTION, result is 24 which is 4!
Every time you are calling the function prod recursively, the current function prodA is paused (saving the values of its variables in memory) to execute the new function prodB until prodB returns something to prodA. Then A continues to execute itself (loading back its values from memory)

How to fix a java.lang.StackOverflowError [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
My teacher makes us do these error fixing assignments, and I just can't fix this one. That's why I came here. I want to ask for one favor and a few questions
Questions: What does the error message mean in detail(I just want to know for my own curiosity), Why does it occur specifically using my code, How can I fix it
Favor: Can u please fix my code, Sorry if this seems like a way to get an answer but I'm a bit lost.
Here's the code
public class Recursion
{
public static void indifferent( int x, int y )
{
System.out.print( x );
indifferent( x - 1, y + 2 );
System.out.print( y );
}
}
public class RecursionDriver//-the driver class
{
public static void main( String [] args )
{
Recursion.indifferent( 7, -1 );
}
}
If you examine the code it should be obvious that it can never terminate. Every call to indifferent makes another call to indifferent. Unconditionally.
The StackOverflowError happens because the nested calls have gotten too deep. Java method calls use a stack to hold local variables (and the return address, and other stuff). The stack has a fixed size. If you have too many nested calls, the stack overflows.
How to fix it? Rewrite the code to do what it is currently doing, but without using recursion.
But first you need to understand what it is doing. How do you do that? Well ... basically ... you read the code.
Well I'm not completely sure what indifferent means because this is what my teacher told us to put as the name for the class(she said its meaningless and told us to ignore it)
Yup. Ignore the name, and read what the code actually does. If you can't figure it out ... then "hand execute" it using a pencil and paper.
In recursion you try to divide your problem in sub problems and try to compute the result. Hence, in recursion you always need to have a base case. Base case in the final depth of your recursion. Once you reach the base case you start coming out of the recursion and get you final answer.
In your code:
public static void indifferent( int x, int y )
{
System.out.print( x );
indifferent( x - 1, y + 2 );
System.out.print( y );
}
You do not have a base case, do your code just keeps going deep in recursion.
public static void indifferent( int x, int y )
{
if(x == 1) //example of a base case
return;
System.out.print( x );
indifferent( x - 1, y + 2 );
System.out.print( y );
}

Formula with Recursion (n+(n-1)+n) error [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I need to use recursion to calculate how many medals a player gets for example if I enter 3 the player got 8 medals [Ex1.(3+(3-1)+3)=(3+2+3)=8]/[Ex2.(5+(5-1)+5)=(5+4+5)=14] When I enter 1 on the main method to test it works but when I change a number greater than 1 it crashes and I get red letters as error this is the error I get. I have done about 5 recursion methods already but I'm stuck on this one.
java.lang.StackOverflowError
at RecursiveFunctions.countMedals(RecursiveFunctions.java:87)
public class RecursiveFunctions{
public static int countMedals(int n){
if(n==0){
return 1+(1-1)+1;
}
else{
return countMedals((n)+(n-1)+(n));
}
public static void main(String[] args){
System.out.println("Number of Medals: " + RecursiveFunctions.countMedals(3));
}
}
Try tracing through the function to see what happens:
countMedals(3) returns countMedals(3 + 2 + 3)
countMedals(8) returns countMedals(8 + 7 + 8)
This is going to continually grow, and never hit your base case of 0.
Your formula has no recursive logic. There is no iteration, it's just a simple math equation.
public static int countMedals(int n){ return 3*n - 1;}
You recursive method has no endpoint in the recursive calls.
You call:
countMedals((n)+(n-1)+(n))
If n is 2, this expression evaluates:
countMedals((2)+(2-1)+(2)) -> countMedals(5)
And this is:
countMedals((5)+(5-1)+(5)) -> countMedals(14)
And so on... You never stop. So you stack is full, and Java crashes.
From your code, it looks like you will never reach the case where n == 0. This is why you are entering infinite recursion.
Each time you call your function with n + (n - 1) + n, which is essentially 3n - 1. So what you have is f(n) = 3n - 1, and you're passing the result of that into the function itself. Now f(n) = 0 only when n = 1 / 3. Can you see any way where n can ever be 1 / 3?
Also, try plotting this function on a graph. What do you see happening to the y values as you keep increasing x (basically n in this case)?
I don't see how you can apply recursion like this. To compute f(n) you need to compute f(3n-1), for which you need to compute f(f(3n-1)), etc. It never terminates, so you get a stack overflow.
In fact I don't know why you are recursing at all, if f(3) and f(5) both = 3n-1. Evidently you haven't understood your problem correctly.

Categories

Resources