Small Steps III — Thinking with Programs

Remembering a value's position

Remember the position of a value.

What you will learn

Remembering an index instead of a value lets you know both what the smallest value is and where it is.

Try it

Example · example2.cpp
void small_main()
{
    Array<int> numbers = {7, 2, 9, 1, 5};
    int smallest_index = 0;

    for (int i = 1; i < numbers.length(); i = i + 1)
        if (numbers[i] < numbers[smallest_index])
            smallest_index = i;

    print("Smallest: ", numbers[smallest_index]);
    print("Index: ", smallest_index);
}

smallest_index is the position of the smallest element. Read its value with numbers[smallest_index]. In this example, the smallest value is 1 at position 3.

Index in the variable name helps distinguish a position from a value. If the minimum occurs several times, the current < comparison keeps its first occurrence.

Exercise

Find the index of the largest value, and print both the value and its index.

Exercise starter · exercise2_starter.cpp
void small_main()
{
    Array<int> numbers = {4, 11, 6, 20, 9};

    // find the index of the largest value.
}

Hint

Start largest_index at 0 and compare numbers[i] > numbers[largest_index].

show solution
void small_main()
{
    Array<int> numbers = {4, 11, 6, 20, 9};
    int largest_index = 0;

    for (int i = 1; i < numbers.length(); i = i + 1)
        if (numbers[i] > numbers[largest_index])
            largest_index = i;

    print("Value: ", numbers[largest_index]);
    print("Index: ", largest_index);
}
← Previous lessonNext lesson →