Post-Increment in Recursive Method? [duplicate] - java

This question already has answers here:
Post-increment and Pre-increment concept?
(14 answers)
Java: Prefix/postfix of increment/decrement operators
(11 answers)
Closed 6 years ago.
I'm trying to learn java oop and i find some problem understanding why the use of post-increment in Recursive Method cause error ? I don't understand .
Main Class :
public class Main {
public static void main(String[] args) {
A a = new A();
a.res(0);
}
}
Code work fine :
public class A {
public void res(int a){
if (a < 5)
res(a+1);
System.out.println(a);
}
}
Output : run:
5
4
3
2
1
0
BUILD SUCCESSFUL (total time: 0 seconds)
But in when i use the ++ operator i got StackOverflowError .
public class A {
public void res(int a){
if (a < 5)
res(a++);
System.out.println(a);
}
}

You are confusing a++ and ++a. As per java documentation - "The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value".
In your case the recursive method is always called with the argument 0

The post-increment operator increments the variable after you use it, so it will only increment the variable after the recursive function is returned.
Your code is doing this:
res(a++) //a = 0
//now a = 1
The recursion will never reach that next line, so the recursive function will always call res(0)
References: https://stackoverflow.com/a/2371162/7238307

Well... what do you expect, exactly? Let's re-write your program slightly. Your program (the one that crashes) can effectively be re-written like so, achieving the same effect (that is, crashing due to a StackOverflowError):
public class A {
public void res(int a){
if (a < 5) {
res(a);
++a;
}
System.out.println(a);
}
}
Your variable a will only increment after the recursive call to res has completed... which is never, because you're always invoking res with the same value.

This is how the recusrive calls are resolved with a+1.
a=0, res(0)
+ 0 < 5, res(1)
++ 1 < 5, res(2)
+++ 2 < 5, res(3)
++++ 3 < 5, res(4)
+++++ 4 < 5, res(5)
++++++ 5 = 5, print 5
+++++ print 4
++++ print 3
+++ print 2
++ print 1
+ print 0
Regarding the problem of your code with a++ is that the increment is performed after the the recursive call is performed. So you basically get:
a=0, res(0)
+ 0 < 5, res(0)
++ 0 < 5, res(0)
+++ ...

Related

Following snippet doesn't produce expected result

I found this in one of the Java programming quiz question.
public class Calculator {
public static void main(String[] args) {
int i = 0;
Calculator c = new Calculator();
System.out.print(i++ + c.opearation(i));
System.out.print(i);
}
public int operation(int i) {
System.out.print(i++);
return i;
}
}
Executing above snippet gives me the result of 121. I'm expecting it to be 111. I'll explain how I interpreted it.
+ addition operator would get executed from right to left (ref: operator precedence). So, c.operation(0) is invoked first and it prints the value 1 instead I'm expecting the value to be 0 since System.out.print prints the value of i first and then increments the i value since it is a post increment operator.
Secondly, the i value 1 is returned to the main and the statement System.out.print(i++ + 1) gets executed now. And since i has post increment operator it should have executed like 0 + 1 and produced the result 1 insted it printed result as 2.
Thirdly, the i value is now incremented to 1 and this gets printed as expected.
In short, I'm expecting the value to be printed as 011 but I got the result as 121. I'm not sure where my interpretation goes wrong.
Additive Operators
The additive operators have the same precedence and are syntactically
left-associative (they group left-to-right).
int i = 0;
System.out.print(i++ + c.operation(i));
evaluate i++, get left operand 0, and increment i to 1.
pass i(1) to c.operation(i), execute System.out.print(i++). Print 1 then return 2(right operand).
i++ + c.operation(i) ---> 0 + 2, print 2.
print 1.

JAVA program always gives the wrong output for the first iteration and then works correctly [duplicate]

I was going through some exercises but I am confused in this one:
public static int f (int x, int y) {
int b=y--;
while (b>0) {
if (x%2!=0) {
--x;
y=y-2;
}
else {
x=x/2;
b=b-x-1;
}
}
return x+y;
}
What is the purpose of b=y--?
So, for example, x=5 and y=5
when we first go inside of while loop (while (b>0)) will b = 4 or 5? When I am running the code in my computer b is 5. And the return is 3. It is really unclear to me. Sorry if I am unclear in my question.
int b=y--; first assignes b=y and then decrements y (y--).
Also take a look at the prefix/postfix unary increment operator.
This example (taken from the linked page) demonstrates it:
class PrePostDemo {
public static void main(String[] args){
int i = 3;
i++;
// prints 4
System.out.println(i);
++i;
// prints 5
System.out.println(i);
// prints 6
System.out.println(++i);
// prints 6
System.out.println(i++);
// prints 7
System.out.println(i);
}
}
The difference between a post-increment/decrement and a pre-increment/decrement is in the evaluation of the expression.
The pre-increment and pre-decrement operators increment (or decrement) their operand by 1, and the value of the expression is the resulting incremented (or decremented) value. In contrast, the post-increment and post-decrement operators increase (or decrease) the value of their operand by 1, but the value of the expression is the operand's original value prior to the increment (or decrement) operation.
In other words:
int a = 5;
int b;
b = --a; // the value of the expression --a is a-1. b is now 4, as is a.
b = a--; // the value of the expression a-- is a. b is still 4, but a is 3.
Remember that a program must evaluate expressions to do everything. Everything is an expression, even just a casual mention of a variable. All of the following are expressions:
a
a-1
--a && ++a
System.out.println(a)
Of course, in the evaluation of expressions, operator precedence dictates the value of an expression just as the PEMDAS you learned in grade school. Some operators, such as increment/decrement, have side effects, which is of course great fun, and one of the reasons why functional programming was created.
I believe b would equal 5 entering the loop because
b=y--;
When the "--" is behind the variable it decrements it after the action.
It's poor coding, as it can confuse new programmers.
The function, assuming it is passing by value, like in the example above (as opposed to passing by reference) takes a copy of y, decrements it, and assigns it to b. It does not alter the argument passed to the function when it was called.
Post increment
x++;
x += 1;
Post decrement
x--;
x -=1;
Pre increment : ++x;
Pre decrement : --x;
According to the Head First Java:
Difference between x++ and ++x :
int x = 0; int z = ++x;
Produces: x is 1, x is 1
in x = 0; int z = x++;
Produces: x is 1, z is 0

Does anyone know how to work this out? [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 7 years ago.
Improve this question
What output is produced by the following program?
The answer says 7 but i have trouble working it out.
public class practice {
public static void main(String[] args){
int i = 5;
int b = g(i);
System.out.println(b+i);
}
public static int f(int i) {
int n = 0;
while (n * n <= i) {n++;}
return n-1;
}
public static int g(int a) {
int b = 0;
int j = f(a);
b = b + j;
return b;
}
}
I assume main is getting called. Here is a list of steps that happen
g gets called with 5 as its parameter.
then in function g, f gets called with g's parameter, which is 5
In function f n is set to zero, a while loop is called and every time n*n is less than or equal to its parameter, which is 5, n is incremented. below outlines the while loop.
0*0 is less than 5, increment n from 0 to 1 and continue.
1*1 is less than 5, increment n from 1 to 2 and continue.
2*2 is less than 5, increment n from 2 to 3 and continue.
3*3 is not less than 5, break out of the loop.
n-1, which is 3-1=2, gets returned back to where it was called, in variable j in function g.
b gets assigned to b+j which is 0+2.
b gets returned back to variable b in function main.
b+i, which is 5+2, which is 7, gets printed as the answer.
Your using a number (5) and basically checking what is the first whole number squared that equals more than than 5. Then you negate 1 from the answer and add 5.
So here is the maths:
1. Find the first whole number squared that is larger than 5
0*0 = 0 //+1
1*1 = 1 //+1
2*2 = 4 //+1
3*3 = 9 //3*3 is the first value over 5; loop breaks
2. Negate 1 from 3 (the first whole number when squared that is larger than
3 - 1 = 2; //using 3, negate 1 (also could have used n--)
3. Using the final value 2 add 5
2 + 5 = 7 //using 2 add 5
Answer is 7.
There is some really unnecessary stuff in this code, such as the two extra methods.

Learning Java - Do not fully understand how this sequence is calculated (Fibonacci) in for loop [duplicate]

This question already has answers here:
Java recursive Fibonacci sequence
(37 answers)
Closed 8 years ago.
I am learning Java and I have this code from the internet and running it in Eclipse:
public class Fibonacci {
public static void main (String [] args) {
for (int counter = 0; counter <= 3; counter++){
System.out.printf("Fibonacci of %d is: %d\n", counter, fibonacci(counter));
}
public static long fibonacci(long number) {
if ((number == 0) || (number == 1))
return number;
else
return fibonacci(number - 1) + fibonacci(number - 2);
}
}
I've tried to understand it but cannot get it. So I run through the code and counter gets passed in through the fibonacci method. As counter starts at 0 and this is what gets passed first, then 1 and I understand the method passes back 0 and then 1.
When it reaches 2: it will return 2-1 + 2-2 = 2 and it does return this.
When it reaches 3: it will return 3-1 + 3-2 = 3 but it does not return 3 it returns 2.
Please can someone explain to me why as I cannot figure this out?
Thanks
First, I have to tell you that this recursive version has a dramatic exponential cost. Once you understand how it works, my advice for you would be to learn about tail recursivity, write a tail-recursive solution, an iterative solution, and compare them to your current method for high values of "number".
Then, your function basically uses the mathematical definition of the Fibonacci sequence :
f0 = 1, f1 = 1, fn = fn-1 + fn-2 for all n >= 2
For example if we call fibonacci(3), this will return fibonacci(2) + fibonacci(1). fibonacci(2) will be executed first and will return fibonacci(1) + fibonnacci(0). Then fibonacci(1) will return immediately 1 since it is a terminal case. It happens the same thing with fibonnacci(0), so now we have computed fibonnacci(2) = 1 + 0 = 1. Let's go back to fibonacci(3) which has been partially evaluated at this point : 1 + fibonnacci(1). We just have to compute fibonnacci(1) and we can finally return 1 + 1 = 2.
Even in this little example, you can see that we evaluated twice fibonacci(1), that is why this version is so slow, it computes many times the same values of the sequence, and it gets worth when "number" is high.

I don't know why my variables are getting these values [duplicate]

This question already has answers here:
Java: Prefix/postfix of increment/decrement operators
(11 answers)
Closed 9 years ago.
public int Gauss_Jordan(double[][] matrix, int numOfRows, int numOfCols) {
for (int col_j = 0; col_j<numOfCols; col_j++) {
row_i = nonzeros ++;
System.out.println(row_i+" and "+nonzeros);
}
//return matrix;
return 0;
}
up above in the method called "Gauss_Jordan", you can see a for loop where it iterates until a certain condition is met. (duh.. lol sorry).
so i set row_i = nonzeros++ but here's the thing, when I print out each iteration i get
0 and 1,
1 and 2,
2 and 3
. I would expect the output to be:
1 and 1,
2 and 2,
3 and 3.
How come this is not the case?
You'd need ++nonzeros instead of nonzeros++ to get what you expect.
Thats called post-increment;
When you say row_i = nonzeros ++;
first the row_i will get assigned with the value of nonzeros and the nonzero will get incremented.
try pre-increment
row_i = ++nonzeros;
If pre-increment is not what you wanted. Check the initialization of nonzeros and change it into '1` for it to show up as you want. Your codes are functioning as they should.

Categories