---
title: "Arrays in Programming: Indexes, Loops, Search, Max and Min: Programming Fundamentals (10)"
date: "2026-10-18"
description: "Learn one dimensional arrays: declare them with Dimension, load and traverse them with loops, search a value, and find the sum, average, maximum and minimum."
tags: ["Programming Fundamentals", "Tutorials"]
url: "https://rolandoandrade.me/blog/programming-fundamentals-arrays/"
author: "Rolando Andrade"
---

# Arrays in Programming: Indexes, Loops, Search, Max and Min: Programming Fundamentals (10)

> Learn one dimensional arrays: declare them with Dimension, load and traverse them with loops, search a value, and find the sum, average, maximum and minimum.

An array is one variable that holds many values of the same type, in numbered boxes. Instead of ten variables for ten grades, you use one array with ten boxes, and you pick a box by its number. In this lesson you declare arrays, fill them with a loop, walk through them, search for a value, and calculate the sum, the average, the largest value and the smallest value.

In this lesson you will:

- Declare an array with `Dimension` and pick one box with an index, like `a[3]`.
- Load an array from user input with a `For` loop.
- Traverse an array forward and backward.
- Search an array for a value.
- Calculate the sum, average, maximum and minimum of an array.

It takes about 35 minutes. You need a browser. Every example runs in the page.

## Why one name for many values

Say you want the average of five grades. With what you know so far, you need five variables: `grade1`, `grade2`, up to `grade5`. Now make it fifty grades. You would write fifty variables and fifty `Read` lines. If the number of grades changes, you rewrite the program.

An array solves this. All the grades live under one name, and a number picks each one. Because the number can be a variable, a [loop](/blog/programming-fundamentals-loops/) can visit every box with three lines of code. Fifty grades take the same code as five.

Arrays are also where many real bugs live. Almost every program an AI agent writes for you has a loop over an array. A generated loop that starts at the wrong index, or stops one box too early, still runs. It gives a wrong answer that looks right. To catch it, you need to know exactly which boxes exist and which ones hold data. That is what this lesson trains.

## How an array works

The course defines an array as a finite, static and ordered set of elements of the same type. Each word matters:

- **Finite.** It has a fixed number of boxes.
- **Static.** That number is set before the program runs and never changes.
- **Ordered.** Every box has a position, so there is a first, a second and a last.
- **Same type.** All boxes hold `Integer` values, or all hold `String` values, never a mix.

You declare an array in two lines. `Define a As Integer;` gives the type of the boxes, and `Dimension a[10];` gives the number of boxes. StepCode also accepts a one line form, `Define a As Integer[10];`, which you may find in other code. This series always uses `Define` with `Dimension`, the form of PSeInt and of the course.

An **index** is the number of a box. In StepCode, indexes start at 1, as they do for [strings](/blog/programming-fundamentals-strings/#the-tools-for-strings), so `a` has boxes `a[1]` to `a[10]`. You read and write a box like a normal variable: `a[3] <- 15;` stores 15 in box 3, and `Write a[3];` shows it.

Most programs reserve more boxes than they need, like 10, and then ask the user how many they will use. That number is usually called `n`. The boxes after `n` exist, but they have no value yet.

*Figure: Dimension a[10] reserves ten boxes, and the user filled n = 5 of them. Move the index: boxes 6 to 10 exist but have no value yet, and 0 or 11 are outside the array.*

Two operations appear in almost every array program:

- **Loading** means filling the boxes, usually with a `For` loop and a `Read` inside.
- **Traversing** means visiting the boxes one by one, from the first position to the last, adding 1 to the index each time.

## Build programs with arrays

Each part below is a complete program. Press Run, type the inputs shown, and compare your output.

### 1. Load five numbers and print them backward

This is the first array activity from the course slides. The program loads five numbers, then traverses the array from the last box to the first. `Step -1` makes the loop count down.

**Part 1: reverse order** (StepCode)

```stepcode
Program ReverseFive
    Define numbers As Integer;
    Dimension numbers[5];
    Define i As Integer;

    For i <- 1 To 5 Step 1 Do
        Write "Enter number ", i, ":";
        Read numbers[i];
    EndFor

    Write "In reverse order:";
    For i <- 5 To 1 Step -1 Do
        Write numbers[i];
    EndFor
EndProgram
```

Type `4`, `8`, `15`, `16` and `23`.

You should see:

```
Enter number 1:
Enter number 2:
Enter number 3:
Enter number 4:
Enter number 5:
In reverse order:
23
16
15
8
4
```

The program keeps all five numbers until the end. With single variables and no array, you could not print them backward without five separate names.

### 2. Sum and average a list of grades

Now the user decides how many values to type, up to 10. The program reads `n` first, loads `n` boxes, and then traverses the same `n` boxes to add them up. The variable `total` is an **accumulator**, the pattern from [Loops](/blog/programming-fundamentals-loops/#counters-and-accumulators). It starts at 0 and grows by one value in each iteration.

**Part 2: sum and average** (StepCode)

```stepcode
Program SumAndAverage
    Define grades As Real;
    Dimension grades[10];
    Define n, i As Integer;
    Define total As Real;

    Write "How many grades? (max 10)";
    Read n;

    For i <- 1 To n Step 1 Do
        Write "grade[", i, "]:";
        Read grades[i];
    EndFor

    total <- 0;
    For i <- 1 To n Step 1 Do
        total <- total + grades[i];
    EndFor

    Write "Sum: ", total;
    Write "Average: ", total / n;
EndProgram
```

Type `4`, then `15`, `18`, `12` and `20`.

You should see:

```
How many grades? (max 10)
grade[1]:
grade[2]:
grade[3]:
grade[4]:
Sum: 65
Average: 16.25
```

Both loops stop at `n`, not at 10. The boxes from 5 to 10 were never filled, so the program never touches them.

### 3. Find the largest and smallest value

This exercise comes from the course practice guide. To find the maximum, the program assumes the first box is the largest so far. Then it traverses the rest. Every time it finds a larger value, it keeps that one instead. The minimum works the same way with `<`.

**Part 3: minimum and maximum** (StepCode)

```stepcode
Program MinAndMax
    Define a As Integer;
    Dimension a[10];
    Define n, i, smallest, largest As Integer;

    Write "Enter n (max 10):";
    Read n;
    For i <- 1 To n Step 1 Do
        Write "a[", i, "]:";
        Read a[i];
    EndFor

    smallest <- a[1];
    largest <- a[1];
    For i <- 2 To n Step 1 Do
        If a[i] < smallest Then
            smallest <- a[i];
        EndIf
        If a[i] > largest Then
            largest <- a[i];
        EndIf
    EndFor

    Write "The minimum is: ", smallest;
    Write "The maximum is: ", largest;
EndProgram
```

Type `4`, then `1`, `2`, `3` and `2`.

You should see:

```
Enter n (max 10):
a[1]:
a[2]:
a[3]:
a[4]:
The minimum is: 1
The maximum is: 3
```

*Figure: smallest and largest start with a[1] and change only when a box beats them. Try the all negative list to see why a largest that starts at 0 gives a wrong answer.*

Why start with `a[1]` and not with 0? If every value were negative, a maximum that starts at 0 would stay at 0, and 0 is not even in the array. Starting with a real value from the array is always safe. In [Procedures and functions](/blog/programming-fundamentals-procedures-and-functions/#2-add-sum-max-and-min) you turn the sum, the maximum and the minimum into functions you can reuse.

### 4. Search for a word

A **sequential search** checks each box in order until it finds the value or reaches the end. You saw it with strings in the [previous lesson](/blog/programming-fundamentals-strings/). Here the program searches an array of words, from the course practice guide. The variable `position` starts at 0, which means "not found yet". The loop stops as soon as it finds a match.

**Part 4: sequential search** (StepCode)

```stepcode
Program SearchWord
    Define words As String;
    Dimension words[10];
    Define target As String;
    Define n, i, position As Integer;

    Write "Enter n (max 10):";
    Read n;
    For i <- 1 To n Step 1 Do
        Write "a[", i, "]:";
        Read words[i];
    EndFor

    Write "Search:";
    Read target;

    position <- 0;
    i <- 1;
    While i <= n And position = 0 Do
        If words[i] = target Then
            position <- i;
        EndIf
        i <- i + 1;
    EndWhile

    If position > 0 Then
        Write target, " is at position ", position;
    Else
        Write target, " is not in the array";
    EndIf
EndProgram
```

Type `3`, then `dog`, `cat` and `helicopter`, and search for `cat`.

You should see:

```
Enter n (max 10):
a[1]:
a[2]:
a[3]:
Search:
cat is at position 2
```

Run it again and search for `plane`. You should see `plane is not in the array`. A `While` fits better than a `For` here, because the loop has two reasons to stop: the end of the data, or a match.

### 5. Multiply weights by inputs, like a neural network

The course guide had a fun one. An artificial neuron, the basic piece of a neural network, multiplies an array of weights `w` by an array of inputs `x`, box by box, and adds the results. Mathematicians call this the dot product. It is the same accumulator from part 2, with a multiplication inside.

**Part 5: weighted sum** (StepCode)

```stepcode
Program WeightedSum
    Define w, x As Real;
    Dimension w[10];
    Dimension x[10];
    Define n, i As Integer;
    Define result As Real;

    Write "Enter n (max 10):";
    Read n;
    For i <- 1 To n Step 1 Do
        Write "w[", i, "]:";
        Read w[i];
    EndFor
    For i <- 1 To n Step 1 Do
        Write "x[", i, "]:";
        Read x[i];
    EndFor

    result <- 0;
    For i <- 1 To n Step 1 Do
        result <- result + w[i] * x[i];
    EndFor

    Write "The result is ", result;
EndProgram
```

Type `5`, then the weights `4`, `5`, `6`, `4`, `5`, then the inputs `10`, `8`, `4`, `3`, `8`.

You should see:

```
Enter n (max 10):
w[1]:
w[2]:
w[3]:
w[4]:
w[5]:
x[1]:
x[2]:
x[3]:
x[4]:
x[5]:
The result is 156
```

Check it by hand: 4×10 + 5×8 + 6×4 + 4×3 + 5×8 = 40 + 40 + 24 + 12 + 40 = 156. The models that write code today run this same operation billions of times, on much bigger arrays.

## Common mistakes

If you see `Index 0 is outside "a": its positions run from 1 to 5.`, it means a loop started at 0. In StepCode, the first box is `a[1]`. Start your loops at 1.

If you see `Index 11 is outside "a": its positions run from 1 to 10.`, the user typed an `n` larger than the array. `Dimension a[10]` gives exactly ten boxes. Make the array big enough, or check that `n` is at most 10 before you load it.

If you see `"a[4]" has no value yet: give it one before using it.`, it means a loop went past the boxes you filled. This happens when you load `n` values but traverse up to 10. Every loop after the loading must stop at `n`.

If you see `An array size has to be a positive whole number known in advance.`, you wrote something like `Dimension a[n];`. Arrays are static, so the size must be a fixed number. Reserve the most you need, like `Dimension a[10];`, and keep the real count in `n`.

## Arrays, lists and strings

People often say "array" and "list" as if they were the same thing. They are not.

| | Array | List |
| --- | --- | --- |
| Size | Fixed before the program runs | Grows and shrinks while it runs |
| Types | All boxes have one type | Can mix types in many languages |
| Insert in the middle | Shift every box after it one place right | One call, like `insert` |
| Where you see it | Pseudocode, C, Java | Python, JavaScript |

A string is close to an array of characters, but it is its own type with its own tools, like `Substring`.

Python uses lists by default, and its indexes start at 0. The same sum looks like this:

```python
grades = [15, 18, 12, 20]
total = 0
for i in range(len(grades)):   # i goes 0, 1, 2, 3
    total = total + grades[i]
print(total / len(grades))     # 16.25
```

When you read array code from any source, ask three questions. Where does the index start? Where does the loop stop? Which boxes really hold data?

## Practice exercises

These exercises come from the course practice guide for arrays. Try each one in an empty editor first. Then compare with the solution.

### Remove the even numbers

Write a program that removes the even numbers from an array of up to 10 numbers. To remove a box, shift every box after it one place to the left, and subtract 1 from `n`.

Inputs `5`, then `1`, `2`, `4`, `3`, `6` give:

```
Enter n (max 10):
a[1]:
a[2]:
a[3]:
a[4]:
a[5]:
Without evens: 1 3 
```

**Solution: remove the even numbers** (StepCode)

```stepcode
Program RemoveEvens
    Define a As Integer;
    Dimension a[10];
    Define n, i, j As Integer;

    Write "Enter n (max 10):";
    Read n;
    For i <- 1 To n Step 1 Do
        Write "a[", i, "]:";
        Read a[i];
    EndFor

    i <- 1;
    While i <= n Do
        If a[i] Mod 2 = 0 Then
            For j <- i To n - 1 Step 1 Do
                a[j] <- a[j + 1];
            EndFor
            n <- n - 1;
        Else
            i <- i + 1;
        EndIf
    EndWhile

    WriteNoNewline "Without evens: ";
    For i <- 1 To n Step 1 Do
        WriteNoNewline a[i], " ";
    EndFor
    Write "";
EndProgram
```

*Figure: When a box is removed, the boxes after it slide one place left and n shrinks. Watch i stay where it is after each removal.*

Notice that `i` does not move forward after a removal. The next value has just moved into box `i`, so the program must check that box again.

### Largest jump between neighbors

Write a program that finds the largest difference between two numbers that sit next to each other in the array.

Inputs `5`, then `22`, `10`, `100`, `20`, `19` give:

```
Enter n (max 10):
a[1]:
a[2]:
a[3]:
a[4]:
a[5]:
The maximum difference between neighbors is 90
```

**Solution: largest jump** (StepCode)

```stepcode
Program MaxConsecutiveDifference
    Define a As Integer;
    Dimension a[10];
    Define n, i, difference, maxDifference As Integer;

    Write "Enter n (max 10):";
    Read n;
    For i <- 1 To n Step 1 Do
        Write "a[", i, "]:";
        Read a[i];
    EndFor

    maxDifference <- Abs(a[2] - a[1]);
    For i <- 2 To n - 1 Step 1 Do
        difference <- Abs(a[i + 1] - a[i]);
        If difference > maxDifference Then
            maxDifference <- difference;
        EndIf
    EndFor

    Write "The maximum difference between neighbors is ", maxDifference;
EndProgram
```

The jump from 10 to 100 is 90. The loop stops at `n - 1` because `a[i + 1]` must still be a real box.

### Sort with bubble sort

Write a program that sorts up to 10 numbers from largest to smallest with the bubble sort method from the course. Compare each box with the next one, from the first to the next to last. If they are in the wrong order, swap them. After one full pass, the smallest value has "bubbled" to the end, so the next pass checks one box less.

Inputs `4`, then `1`, `7`, `3`, `5` give:

```
Enter n (max 10):
a[1]:
a[2]:
a[3]:
a[4]:
Sorted: 7 5 3 1 
```

**Solution: bubble sort** (StepCode)

```stepcode
Program BubbleSortDescending
    Define a As Integer;
    Dimension a[10];
    Define n, i, j, temp As Integer;

    Write "Enter n (max 10):";
    Read n;
    For i <- 1 To n Step 1 Do
        Write "a[", i, "]:";
        Read a[i];
    EndFor

    For i <- 1 To n - 1 Step 1 Do
        For j <- 1 To n - i Step 1 Do
            If a[j] < a[j + 1] Then
                temp <- a[j];
                a[j] <- a[j + 1];
                a[j + 1] <- temp;
            EndIf
        EndFor
    EndFor

    WriteNoNewline "Sorted: ";
    For i <- 1 To n Step 1 Do
        WriteNoNewline a[i], " ";
    EndFor
    Write "";
EndProgram
```

*Figure: Each step compares two neighbors and swaps them when the left one is smaller. After each pass, one more box at the end is in its final place.*

The swap needs a third variable, `temp`, just like the [swap](/blog/programming-fundamentals-variables-and-data-types/#5-swap-two-variables) in Variables and data types. If you write `a[j] <- a[j + 1];` first, the old value of `a[j]` is gone. Change `<` to `>` in the `If` to sort from smallest to largest. Bubble sort comes back in [Procedures and functions](/blog/programming-fundamentals-procedures-and-functions/#4-reverse-and-sort), [Files](/blog/programming-fundamentals-files/#sort-numbers-from-a-file) and the [final project](/blog/programming-fundamentals-final-project/#exercise-2-the-best-scores-list).

All the editors on this page run on [StepCode](/projects/stepcode/), the pseudocode language I built for my students at UCAB.

## What you learned

- An array is one variable with a fixed number of boxes of the same type. `Define` sets the type and `Dimension` sets the size.
- An index picks one box. In StepCode, indexes run from 1 to the size of the array.
- Reserve enough boxes, keep the real count in `n`, and make every loop stop at `n`.
- Loading uses a `For` loop with `Read`. Traversing uses a `For` loop that visits every box.
- Sum, average, maximum, minimum and search are all one traversal with a small job inside.

## Next steps

An array is a row of boxes. In the next lesson, [matrices](/blog/programming-fundamentals-matrices/), you add a second dimension: rows and columns, like a table or a chessboard. You will load and traverse them with two nested loops and work with their diagonals.
