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.
Related
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.
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)
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
I have two methods, that I believe can be made better way, but can't find this way.
First:
public int calcPow(long num) {
int count = 0;
while(num/2!=0) {
num = num/2;
count++;
}
return count;
}
The second is:
private long findParentNumber(long value) {
for(int bitNum = 0; bitNum < Long.SIZE; bitNum++) {
if((value & (1L << bitNum)) != 0) {
return value ^ (1L << bitNum);
}
}
throw new RuntimeException("No parent number found");
}
I believe, there are ways to do the same without loops. Can you help?
Cheers!
For the second one, you're unsetting the lowest set bit. There's a relatively well known bithack to do that, though only relatively because it seems that bithacks in general are not well known.
Anyway, it's
return x & (x - 1);
The logic here is that in x - 1, there's a borrow running through the lowest zeroes until it hits the lowest 1-bit, which it unsets. The lowest zeroes are left set, they are then removed by ANDing it with the original number.
You can write the first one in terms of numberOfLeadingZeros, which would be more obviously correct than floating point hacks which always make you think about how accurate they might be (and in any case they're slow, you might be better off with the loop).
Edit: for completeness, that would be 63 - numberOfLeadingZeros(x), it differs from your definition at x = 0 but that's a bad input anyway.
Try this for the first one.
public int calcPow(long num) {
if (num == 0) return 0;
if (num < 0) num = -num;
return Long.numberOfTrailingZeros(Long.highestOneBit(num));
}
Or this suggested by harold
public int calcPow(long num) {
return num == 0 ? 0
: 63 - Long.numberOfLeadingZeros(Math.abs(num));
}
For the first one, you can use the Math.log method that already exists:
public static int log2(long number) {
return (int) Math.floor(Math.log(number) / Math.log(2));
}
or this faster function suggested by saka1029:
public static int log2(long number) {
return number == 0? 0: Long.numberOfTrailingZeros(Long.highestOneBit((number < 0)? number * -1: number));
}
As you can see I also changed the method to static, since I see no point in having to use an Object to get a log when no object is involved. And secondly I changed the names into something more fitting.
For the second one you can use the bit-wise check operator &:
public static long removeSmallBit(long value) {
return value & (value - 1);
}
Essentially you are removing the smallest bit from the variable, and return that number after you change that bit to 0. And as you can see again I made the method static and changed the name. 2nd answered inspired by this answer submitted by harold
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...
I am trying to understand the working of return statement in JAVA.
My doubt is if inside a method with a Non void return type, I have a decision block which also has a return statement of its own, Still I have to return some value .
For understanding here is a sample code I have written :-
public int bunnyEars(int bunnies) {
//int count=0;
if (bunnies >=1) {
count = count + 2;
bunnyEars(bunnies -1);
return count1;
}
return count2 ;
}
In the mentioned code I just want to return the no. of bunnies which I am being able to do from inside the bunnyEars method count1. But still JAVA wont allow to have a non-void method without a return type which is totally understood and I have to add count2 return also. Now I am suspecting that I am having a conceptual understanding failure here. Kindly let me know if I am missing something? Kindly let me know If I am missing some more info here.
[Edited] Full code:
public class Test5 {
//public int ears=1;
public int count=0;
public int bunnyEars(int bunnies) {
//int count=0;
if (bunnies >=1) {
count = count + 2;
bunnyEars(bunnies -1);
return count;
}
return count ;
}
public static void main(String args[]){
Test5 test5= new Test5();
System.out.println(test5.bunnyEars(90));
}
}
Yes you need to return count2 which should be zero. Which means if there are no bunnies then there are no ears. So which returning you should be returning some value irrespective of the conditional block.
So in this case
return count1;
represents the number of ears if the bunnies are represent, while
return count2;
represents the number of ears when there are no bunnies, which should be 0.
I hope that gives you some clarification
I think your conceptual misunderstanding lies with understanding the flow of the program.
Supposed you were to use this method by calling:
bunnyEars(2)
Then, once you enter the method, the first thing the program does is check if 3 >= 1. Since this is true, you proceed into the code inside the {..} (called a 'block'). Inside this block, you increment count by 2. I am assuming count is defined elsewhere in the class, but suppose the current value for count is 10. Then, the new value of count will be 12.
After this, the program executes the line:
bunnyEars(bunnies - 1)
Which translates to:
bunnyEars(1)
Now, basically, you are calling the same method again, but passing in 1 instead of 2.
Once again, the program checks to see that 1 >= 1, which is true. So it goes into the
if-block which, again, increments count by 2. So now, count = 14. Then it calls the
same method again but this time passing in 0.
bunnyEars(0)
Since 0 >= 1 evaluates to false, you the program skips the if-block and continues
execution after the block. So know, you are in the method bunnyEars(), but you have
completely skipped over your "return" statement. But, alas, bunnyEars MUST return an int.
So this is why you must have a return after the block. In your case, bunnyEars(0) returns count2 and the program-execution returns to where you called bunnyEars(0).
Read up on recursive calls. The basic idea of a recursive method is that, inside the recursive method, you must have some case that terminates the recursion (otherwise you will loop forever).
For example, the following code will go on forever:
public int sum(int in)
{
return in + sum(in - 1);
}
This will keep going on forever, because sum(1) will call sum(0) which calls sum(-1).
So, I must have a condition that terminates the recursion:
public int sum(int in)
{
if(in == 0) return 0;
return in + sum(in - 1);
}
Now, I have a terminating-case. So if I call sum(1), it will call sum(0) which returns 0. So my result is 1 + 0 = 1.
Similarily,
sum(2) = 2 + sum(1) = 2 + 1 + sum(0) = 2 + 1 + 0
sum(3) = 3 + sum(2) = 3 + 2 + sum(1) = 3 + 2 + 1 + sum(0) = 3 + 2 + 1 + 0 = 6
Hope this helps!
So as I understand it, your question is why you still need to return count2 if you return count1. The answer is basically 'what happens if you don't enter the if block?'. In that case, without return count2, you wouldn't have a return value, which is what Java is complaining about. If you really don't want two return statements, you could probably do something like:
public int bunnyEars(int bunnies) {
int count=0;
if (bunnies >=1) {
count = count + 2;
bunnyEars(bunnies -1);
}
return count ;
}
On a side note, this and the code you posted in your question won't work for regression purposes, but the one in your comment does, and there it looks like you have a static variable for count, in which case you could set the return type to void and just print count.