Small Steps I — Creating with Text and Numbers

Creating an array by choosing its size

Create five positions, store 1 through 5 in them, and print them.

What you will learn

Instead of listing initial values, you can choose the number of positions first. Array<int>(3) creates three positions for integers.

Try it

Example · example.cpp
void small_main()
{
    Array<int> numbers(3);
    for (int i = 0; i < numbers.length(); i = i + 1)
    {
        numbers[i] = i + 1;
        print(numbers[i]);
    }
}

Array<int> numbers(3); has three positions. Array<int> numbers = {3}; has one position containing the value 3. Keep the two forms distinct.

Small Array has no operation to increase its length after creation. You can still change each element's value.

Expected output:

1
2
3

Exercise

Create five positions, store 1 through 5 in them, and print them.

Exercise starter · exercise_starter.cpp
void small_main()
{
    Array<int> numbers(3);
    for (int i = 0; i < numbers.length(); i = i + 1)
    {
        numbers[i] = i + 1;
        print(numbers[i]);
    }
}

Hint

Change the parts of the example that you need.

show solution
void small_main()
{
    Array<int> numbers(5);
    for (int i = 0; i < numbers.length(); i = i + 1)
    {
        numbers[i] = i + 1;
        print(numbers[i]);
    }
}
← Previous lessonNext lesson →