Comp 110 For Loops

For Loops

Writing a loop is an extremely common task in programming which usually involves 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 a 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!). 

Also, the counter variable is only defined within the for loop's repeat block. It's kinda like a function call in which the parameter is only accessible within the function body. Therefore, you can have a sequence of for loops that all use i as the counter variable. 

Any while loop can be turned into an equivalent for loop. 

Let's take a look at the first one together!

1. Printing out elements of an array.

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

// can be re-written as:
let arr = [1, 2, 3, 4, 5, 6];
for (let i = 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.

Which Loop Should I Use?

Although for and while loops are interchangeable, there are instances where you want to use one over the other. 

Because a for loop requires you to know in advance how many times the loop will run, it's good to use a for loop when the 'counter' variable is a number.

If your loop requires you to check whether some condition is true or false, a while loop would be a good choice. 

Nested Loops!

When we nest for loops, we are putting one for loop inside of another for loop. Each time we repeat the body of the outer loop, the inner loop starts over and does its looping again.

Here's a spooky example:

import { print } from "introcs";
 
let ghost = "Boo! ";
for (let i = 0; i < 3; i++) {
    for (let j = 0; j < 2; j++) {
        ghost = ghost + "Oo";
    }
    ghost = ghost + " Boo! ";
}
print(ghost); // this prints the string "Boo! OoOo Boo! OoOo Boo! OoOo Boo! "

In this example, the "OoOo" parts of the string come from each time we go through the inner loop. The " Boo! " parts come from each time we go through the outer loop, so when we nest loops we get a combination of what comes from the inner loop and what comes from the outer loop in our string!