Chapter 5 - Arrays
Exercise 1: Accessing Arrays
Create an array with 5
string elements, holding English weekday names: “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”. Then print each array element along with its index.
0 Monday 1 Tuesday 2 Wednesday 3 Thursday 4 Friday
You can assign array elements individually, or you can use an array literal. You can access the elements individually, use a
for loop to get each element index, or use a
for ... range loop to loop over the elements themselves. Better yet, try all these techniques! We’ll show you several solutions incorporating several ways to solve this problem.
When you’re ready, have a look at the solutions.
Exercise 2: Counting Occurrences
We’ve set up a small array that contains the numbers 0, 1, and 2, each repeated a random number of times. Update the program to count how many times each number occurs.
Hint: You can set up a second array to keep track of the number of occurrences. A three-element array will (conveniently) have the indexes 0, 1, and 2…
0 occurred 4 times 1 occurred 3 times 2 occurred 2 times
Extra credit: Now do the same for this array!
Here are our solutions.