Comp 110 for Loops

for Loops

Writing a loop is an extremely common task in programming with three important steps!

1. declaring and initializing a counter variable

2. a test that will check your counter variable against some criteria

3. increment/alter your counter variable in some way

The syntax of for loop gets all three of these key steps taken care of in one line!

for ( <variable initialization>; <boolean test>; <variable modification>) {
    <repeat block>
}

The flow of execution of a for loop is:

variable initialization --> boolean test --> repeat block --> variable modification.

Note that even though the modification of your counter is on the first line, this still happens after the code inside the body of the loop executes. Writing loops in this way helps us to avoid forgetting to increment/decrement our counter variable (goodbye infinite loops!).

Any while loop can be turned into an equivalent for loop. Some good practice with this might be turning the while loops on looping algorithms page into for loops. Let's take a look at the first one together!

1. Printing out elements of an array.

let i: number = 0;
let arr: number[] = [1, 2, 3, 4, 5, 6];
while (i < arr.length) {
    print(arr[i]);
    i++;
}

Can be rewritten as:

let arr: number[] = [1, 2, 3, 4, 5, 6];
for (let i: number = 0; i < arr.length; i++) {
    print(arr[i]);
}

The output for both of these loops will be exactly the same: 1, 2, 3, 4, 5, 6. These two types of loops are completely interchangeable, however, the syntax of a for loop often proves to be preferable as you get more comfortable with the process.