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.
Expected output:
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.
Solution
Here’s a solution that assigns and accesses each array element individually:
Here’s a solution that uses an array literal, and a loop that goes through each element index.
And here’s a solution that uses a for ... range
loop.