Comp 110 Iterating through Arrays

Review Arrays

Remember, arrays hold many items of the same type. These items are called elements and each element is a single item addressed by its index. Indexing of arrays starts at 0 (this is very important!) therefore the first element of an array is always at index 0 and the last element is always at index length of the array - 1. 

Also, remember that all the elements of an array are of the same type: numbers, strings, booleans, etc. 

Let's look at an array we will use as our example:

let c: number[] = [2, 4, 6, 8]

What if we wanted to go through and change each element of the array by dividing it by 2? We can go through each index manually and change the element by dividing it by 2. That would look like this: 

c[0] = c[0] / 2;
c[1] = c[1] / 2;
c[2] = c[2] / 2;
c[3] = c[3] / 2;

print(c);
//This output would be [1, 2, 3, 4]

So we were successful in changing every element in our array by dividing it by 2! But what if we had an array with 100 elements? It would take a very long time to manually change each element in the array by the same amount. We can make this process much easier, faster, and be able to modify very large arrays by utilizing iteration!

Using Iteration

Iteration is working through an array algorithmically. We will be able to quickly access each element in the array and modify it if necessary. Let's apply this idea to our earlier example. 

If we look at the lines where we manually changed the array, we see that each of the lines are exactly the same only the index number is changing. Therefore, we can introduce an index variable and increment it between each line: 

let i = 0;
c[i] = c[i] / 2;
i++;
c[i] = c[i] / 2;
i++;
c[i] = c[i] / 2;
i++; 
c[i] = c[i] / 2;

print(c);
//This output would again be [1, 2, 3, 4]

Because these lines are all exactly the same AND we are repeating them over and over, we can process the array with a for loop:

(for let i = 0; i < c.length; i++) {
       c[i] = c[i] / 2;
}
print(c);
//output is [1, 2, 3, 4]!

Because arrays are indexed starting at 0, we know that the last element in the array will be at array.length - 1. Therefore, by making our boolean test i < array.length, we will go through every element in our array and stop looping after that last element at array.length - 1.