Showing posts with label for loop. Show all posts
Showing posts with label for loop. Show all posts

Trick Question

Today at school we went over the answers of the test we took last time. There was one questions I got totally wrong. A couple people including myself grumbled that it was a trick question. The instructor said it came straight out of the book.

Here is the question: What does the following code snippet output:

int n=0;
for (n=4; n > 0; n--);
{
System.out.println(n);
}

Here is a hint. There is only one line in the output. At first I protested. Surely this code should have 4 lines of output. The loop iterates through four times after all.

The trick was that there was a semicolon directly after the for loop. Therefore the loop has a body which was empty. After the loop finished, n equals 0. Then the program executes one println statement. Yeah. That's an evil question. Now I know better. Watch out for the tricks.