Analyze the following code:

public class Test {
public static void main (String[] args) {
int i = 0;
for (i = 0; i < 10; i++);
System.out.println(i + 4);
}
}

A. The program has a compile error because of the semicolon (;) on the for loop line.
B. The program compiles despite the semicolon (;) on the for loop line, and displays 4.
C. The program compiles despite the semicolon (;) on the for loop line, and displays 14.
D. The for loop in this program is same as for (i = 0; i < 10; i++) { }; System.out.println(i + 4);

Respuesta :

Answer:

C. The program compiles despite the semicolon (;) on the for loop line, and displays 14.

Explanation:

For better representation, the for loop line of the code could also be written as follows:

for( i = 0; i < 10; i++) {

   

   }

System.out.println(i+4);

This means that the for loop will run 10 times and at end of every cycle, the value of i will get incremented by 1. Therefore, at the end of the loop, the value of i = 10.

Note: You would almost think that the value of i at the end of the loop will be 9. But then, don't forget that the value of i gets incremented at the end of each cycle by 1. So at the end of the last cycle of the loop, i will have a value of 10. This is the reason why the loop ends in the first place knowing that the value of i is already 10 which makes the conditional statement of the for loop, (i<10), false.

Continuing, since the value of i at the end of the loop is now 10, the last statement in the code which is as follows:

System.out.println(i+4);

adds 4 to the value of i which gives 14.

Therefore, the console will display a value of 14.

Hope this helps!