Analyze the code below, which utilizes a basic for loop.
int n = 10;
// *prints "Hello World" n times*
for (int count = 0; count < n; count++) {
System.out.println("Hello World");
}
Output:
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Let’s focus on the highlighted portion of the code. All for loops take in three inputs separated by semicolons.
The first input initializes the for loop’s control variable. Like with any variable, you can name it however you wish. Typically, people will call it i, but for the purposes of readability it is called count in the example above. You can also assign any value to the control variable (as long as it works as intended, of course). In this case, count is set to 0 at the beginning of the for loop.
The second input indicates a boolean expression. As long as the expression evaluates to true
, the code within the for loop will be executed. In this case, I have specified that as long as count is less than n, the code inside of the for loop will be executed. Note that this condition is checked at the beginning of each iteration (each cycle) of the for loop.
The last input indicates the action that takes place after each iteration of the loop. Usually, the action changes the control variable so that at some point the condition is false
and the loop terminates. In this case, the action is count++
, which means that after each iteration, the count
variable is incremented by 1. Thus, it will eventually equal the value of n
, which means the condition count < n
will be false
and the loop ends.