Comp 101 Array Examples

Practice with Arrays

Now that we're familiar with the concept of arrays, let's practice using them with a couple more caveats.


Let's start with a style of problem that will become very familiar to us as we get more and more comfortable with arrays: the while loop through the array!

let films: string[] = ["Coco", "Black Panther", "Call Me By Your Name"];
let i: number = 0;
while (i < films.length) {
    print("Wow, I can't wait to see " + films[i]);
    i++;
}

The above code is as simple as it looks -- we declare and initialize an array of strings called films, declare and initialize a number i that will keep track of where we are in the array, and loop through our array using a while loop!

Our console will show the following printed:

Wow, I can't wait to see Coco
Wow, I can't wait to see Black Panther
Wow, I can't wait to see Call Me By Your Name

Let's move on to something a little bit tougher. What if we only want to access the even indices (or in other words, where i is even) of an array?

let films: string[] = ["Coco", "Black Panther", "Call Me By Your Name"];
let i: number = 0;
while (i < films.length) {
    if (i % 2 === 0) {
        print("Wow, I can't wait to see " + films[i]);
    }
    i++;
}

Now that we've added an if-statement of i % 2 === 0, we will print the concatenated statement only when i is even. The array is unchanged, however, how we access items in the array is now different than before.

Our console shows:

Wow, I can't wait to see Coco
Wow,  I can't wait to see Call Me By Your Name

Remember, array's indices start with 0 -- so Coco's index is 0, which is even, and Black Panther's index is 1, which is odd.

Let's continue with something a little more challenging...

    let goodFilms = ["Coco", "Black Panther", "Call Me By Your Name"];
    let haveSeen = [true, true, false];

    let alert: string = "Hey! You really should see ";
    let i: number = 0;

    while(i < goodFilms.length) {
        if (haveSeen[i]) {
            alert = alert + goodFilms[i] + " ";
        }
        i++;
    }

  print(alert);

In the above example we declare two arrays, goodFilms which contains strings and haveSeen which contains boolean values. We also declare a counter variable, i, and a string called alert.

we then loop through our array of strings and if the boolean value at the corresponding index in haveSeen is true we add it to our string.

Our printed result would be:

Hey! You really should see Coco Black Panther