Lesson contents

Arrays and positions

An array keeps items in numbered positions. When you know the position, you can read or replace that item directly.

Simple example

Start with 8, 5 and 9. Read the second item. Changing an item in another position does not change this answer.

Start8 5 9
Result5
Lesson.kt
fun main() {
    var values = intArrayOf(8, 5, 9)
    println(values[1])
}
Output
5
Advertisements

Everyday examples

Find a reserved seat

The tickets in the first three seat pockets are 14, 27 and 32. Which ticket is in the second pocket?

Start14 27 32
Result27

Read the second position. The number printed on that ticket is 27.

Read Wednesday’s temperature

Monday through Wednesday have readings of 18, 21 and 19 degrees. What was Wednesday’s reading?

Start18 21 19
Result19

The days are stored in calendar order. Read the third position to get 19 degrees.

Correct a shelf count

Three bins hold 4, 8 and 6 parcels. A recount shows that the middle bin holds 7. Which values change?

Start4 8 6
Result4 7 6

Replace only the middle value. Both neighbouring counts stay the same.

Cost and limits

Reading a valid position in an array takes constant time. Inserting in the middle of a packed array can require moving every item after it.