Reputation: 11
public class Task {
public static void main(String args[]) {
int x = 0, p = 0, sum = 0;
p = 1;
x = 2;
double q;
sum = 0;
while (p < 12) {
q = x + p - (sum + 5 / 3) / 3.0 % 2;
sum = sum + (x++) + (int) q;
System.out.println(sum);
if (x > 5)
p += 4 / 2;
else
p += 3 % 1;
}
sum = sum + p;
System.out.println(sum);
}
}
While proceeding to line 12 (sum = sum + (x++) + (int)q;
) i thought sum should be 5 but actually the output is 4. I tried line 12 in the interactions pane and indeed saw that sum=4
. I don't get it. Shouldn't x++
yield 3 (x=2) and if this gets added to (int) q ( double q gave me sth like 2.666666), i should be getting 5. Can someone explain to me what happened?
Additionally,after getting my first output, how should I proceed? The next condition is:
if (x > 5)
p += 4 / 2;
else
p += 3 % 1;
since x<5, i should go for the else condition, right?
My last question is that, after using p += 3%1
, my p still remains 1, so do i return back to this loop (since p<12) or do I get out of this loop and proceed to line19? I'm not sure what to do.
Upvotes: 0
Views: 69
Reputation: 1101
At your first time, 3%1=0
p +=3%1
=> p+=0
thats why p still remains 1
Upvotes: 0
Reputation: 1226
In line 12 you are using post increment (x++
). You should use pre increment ++x
.
Post increment puts the current value of x
in your statement, then increases x
.
Pre increment initially increases x
and after that puts result into your statement.
Upvotes: 1