My question has to do with the order in which java checks the conditions of a for loop when there is a print statement in the \"conditions\" of the loop. It
for (int i = -1; i < n; System.out.print(i + " "))
{
i++;
}
First, i
is initialized to-1
(only happens once), and i < n
, so we go into the loop. i
is incremented inside of the for loop, so now i == 0
. We then go to the print statement. Repeat.
The expected behavior that you want would require something like:
for (int i = -1; i < n; i++)
{
System.out.print(i + " ")
}
Here's a reference for the for statement.
The initializer expression happens once. Then the condition is checked, then the body of the loop happens, then the increment expression happens (your print
statement), and then we start over.
The official tutorial is pretty clear if you read through it.
The Java Language Specification entry for the for statement might also be interesting if you want complete details.
A for loop executes the increment step (the third part inside the parentheses) after each execution of the loop. If you switched your print statement and your i++, you would get the result you expect.
for ( <initialization> ; <test> ; <increment> ) {
<body>
}
is equivalent to something like:
<initialization>
while ( <test> ) {
<body>
<increment>
}
So you have:
i = -1;
while ( i < n ) {
i++;
System.out.print(i + " ");
}
The "problem" in your test question is that the types of statements usually put in the <increment>
and <body>
portions are switched.
for(initialization; Boolean_expression; update)
{
//Body
}
Here is the flow of control in a for loop:
The initialization step is executed first, and only once.
Next, the Boolean expression is evaluated.
If Boolean expression is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop means loop is over.
After the body of the for loop executes, the flow of control jumps back up to the update statement. Here your print statement is getting executed.
The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates.
For you below are the steps
in 1st step value of i is -1 at start.
in 2nd step i=-1 is less then n=5 so body will be executed.
in 3rd step i will be incremented to i=0
in 4th step value of i ( which is 0 gets printed)
in 5th step Boolean expression is evaluated again and it returns true as i=0 is less then n=5. so again step 3 ( Body of loop) is executed.