Comp 110 for Loop Statement

for-Loop Syntax

Often while programming, we will want to run through data or simply repeat a given block of statements while a condition is true. A for loop is a very useful tool to accomplish this task. The for loop has three conditions which it works through before working through the body of code: the initial condition, the test condition, and the update condition. The example of the syntax is illustrated below.

for(<initialCondition>; <testCondition>; <updateCondition>) {
    <for body>
}

First, the initial condition is given. A very common initial condition is "int i = 0;". (Note: This initial condition is not limited to this.)

Second, the test condition is given. This condition evaluates to a boolean value like a while loop's test condition. While this condition is true, the for loop will run.

Finally, the update condition is given. A very common update we use is "i++". (Note: This update condition is not limited to this.

The order in which a for loop runs is as follows:

for(1. <initialCondition>; 2. <testCondition>; 4. <updateCondition>) {
    3. <for body>
}

The initial condition is only checked the first time the loop runs (before it enters the body of the loop). After the body of the loop runs, it will update the condition. After updating the condition, it will test the condition again before returning to the body of the loop. This process continues until the test condition is false.

Practice Problems:

How many times would the following for loop run?

for(int i = 3; i > 0; i--){
    //code
}

Answer:

3 times. In this for loop, we have a decrementing i instead of an incrementing i. This is useful to understand for certain situations.

Which of the following is syntactically correct?

int max = 15;
for(int i = 0; i < max; i++){    // 1.
    //code
}

for(int i = 0, i < max, i++){    // 2.
    //code
}

Answer:

1. You must use semicolons to separate your conditions (not commas).

When is it best to use a for loop?

For loops are essentially a specific pattern of while loop with a special syntax. 

  • They are most useful when you use a counting variable.
  • When you are looping a specific number of times
  • When you are looping with a pattern of numbers (0, 5, 10, 15...)