Comp 101 For Loop Examples

For Loop Examples

As we've seen with while loops, looping is an incredibly helpful tool for going through arrays and handling other repetitive logic. However, we still need to work with the same care with which we used while loops. Or else... we'll go on forever.

Let's say we want to learn more about the Summer Olympics now that there's no longer figure skating to look forward to. We have some array of sports, and want to create some corresponding array of booleans that shows if we're interested.

let sports: string[] = ["gymnastics", "volleyball", "rugby", "sailing", "tennis"];
let interested: boolean[];

print(sports.length);
print(interested.length);

Right now, our sports array has a length of 5 and our interested array has a length of 0. We will be growing our interested array so that it also has a length of 5 using a for loop!

for (let i: number = 0; i < sports.length; i++) {
    let hasInterest = promptBoolean("Are you interested in watching " + sports[i] + " this Olympics?");
    if (hasInterest) {
        interested[i] = true;
    } else {
        interested[i] = false;
    }
}

Now we've looped through our entire sports array and for each of the elements we encounter we'll ask our user if they're interested in that sport. We will then record this boolean in our interested array. Now, our interested array has a length of 5 (just like our sports array).

What if we wanted to be really nice and compile a watch list for our friends?

for (let i: number = 0; i < interested.length; i++) {
    let watchList: List<string>;
    if (interested[i]) {
        watchList = cons(sports[i], watchList);
    }
}
print(watchList);

Whoops... it looks like this code doesn't actually work. How come?

It can be a little tricky to spot, but when we declare a variable inside of a for-loop we limit its scope. This basically means that we can't use it outside of that scope and when we try to print it later on the program doesn't know where to look for it! Also, each time we run through the loop our old watchList is lost.

Here is our correct code:

let watchList: List<string>;
for (let i: number = 0; i < interested.length; i++) {
    if (interested[i]) {
        watchList = cons(sports[i], watchList);
    }
}
print(watchList);

Looking good!! See you in Tokyo!

Image result for tokyo 2020