Reputation: 556
Im revising for my SCJA exam at the minute and im confused by this question and answer. The question is what is the result of running and compiling the code.
public class Test{
public static void main(String args[]){
int counter = 0;
for(int i=0; i< 4; ++i){
for(int k=0; k< 4; ++k){
system.out.println("Hello - "+ ++counter);
if((k % 4) == 0)
break;
}
}
}
}
So the answer they give is "Hello-1" because 0 % 4 = 0 But my question is should k not be 1 because its been pre-incremented?
Thanks in advance!
Upvotes: 0
Views: 65
Reputation: 425
k cannot be 1. This is because when a for loop runs, it only updates after it has executed all the code within the loop. Since the loop breaks even before the first iteration is completed, k remains 0.
Upvotes: 0
Reputation: 37813
A for loop has the following structure:
for (initialization; condition; update)
The update
is executed after every execution of the loop.
Therefore the following two loops are identical:
for (int i = 0; i < 10; i++) {
and
for (int i = 0; i < 10; ++i) {
Upvotes: 2
Reputation: 500157
my question is should
k
not be 1 because its been pre-incremented?
The ++k
happens at the end of the loop iteration, i.e. after the if
statement.
It makes no difference whether it's ++k
or k++
; in either case the first value of k
is zero.
So the answer they give is
"Hello-1"
This is clearly incorrect, since counter
is never incremented and stays at zero throughout the program.
Upvotes: 1