Small Steps III — Thinking with Programs

Showing numbers as bars

Show numbers as bars.

What you will learn

Visualization represents data as pictures. Draw taller bars for larger values to see an array.

Try it

Example · example1.cpp
void small_main()
{
    Window window;
    window.open(450, 450);

    Array<int> numbers = {7, 2, 9, 4, 5};

    window.clear(White);

    for (int i = 0; i < numbers.length(); i = i + 1)
    {
        double height = numbers[i] * 30;
        window.fill_rectangle(40 + i * 70, 420 - height, 50, height, Blue);
    }

    window.show();

    while (window.is_open())
        window.show();
}

Multiply each value by 30 for its height. Since y increases downwards, calculate the bar's top as 420 - height.

Change one array value and check that its bar's height changes.

Exercise

First practice the position marker for a sorting animation separately. Draw the bar at current in Red and all others in Blue. This exercise is a static picture and does not sort. Change current from 0 through 4 and check that the red bar moves to that position.

Exercise starter · exercise1_starter.cpp
void small_main()
{
    Window window;
    window.open(450, 450);

    Array<int> numbers = {7, 2, 9, 4, 5};
    int current = 2;

    window.clear(White);

    for (int i = 0; i < numbers.length(); i = i + 1)
    {
        double height = numbers[i] * 30;
        Color color = Blue;

        // Make current red.

        window.fill_rectangle(40 + i * 70, 420 - height, 50, height, color);
    }

    window.show();

    while (window.is_open())
        window.show();
}

Hint

In the drawing loop, choose Color by testing i == current. In the sorting animation, use the position fixed in that step instead of current.

show solution
void small_main()
{
    Window window;
    window.open(450, 450);

    Array<int> numbers = {7, 2, 9, 4, 5};
    int current = 2;

    window.clear(White);

    for (int i = 0; i < numbers.length(); i = i + 1)
    {
        double height = numbers[i] * 30;
        Color color = Blue;

        if (i == current)
            color = Red;

        window.fill_rectangle(40 + i * 70, 420 - height, 50, height, color);
    }

    window.show();

    while (window.is_open())
        window.show();
}
← Previous lessonNext lesson →