Small Steps I — Creating with Text and Numbers

Looking at array values one at a time

Print twice each score. You do not need to store the results back in the array.

What you will learn

Using a loop variable as an array index lets you read the elements in order. length() tells you how many elements there are.

Try it

Example · example.cpp
void small_main()
{
    Array<int> scores = {80, 95, 70};
    for (int i = 0; i < scores.length(); i = i + 1)
    {
        print(scores[i]);
    }
}

The program prints when i is 0, 1, and 2. At 3, i equals the number of elements and the condition becomes false. That is why the condition uses <, not <=. A length of 0 runs no iterations.

Expected output:

80
95
70

Exercise

Print twice each score. You do not need to store the results back in the array.

Exercise starter · exercise_starter.cpp
void small_main()
{
    Array<int> scores = {80, 95, 70};
    for (int i = 0; i < scores.length(); i = i + 1)
    {
        print(scores[i]);
    }
}

Hint

Change the parts of the example that you need.

show solution
void small_main()
{
    Array<int> scores = {80, 95, 70};
    for (int i = 0; i < scores.length(); i = i + 1)
    {
        print(scores[i] * 2);
    }
}
← Previous lessonNext lesson →