📘 CodingMarble Learn

Arrays and Lists: Storing Many Values in One Name

An array is a row of numbered boxes that share one name. Each box holds one value and has an index that starts at 0. We read or change a box with its index, visit every box with a loop (traversal), and use that loop for standard algorithms: sum, average, largest, count and linear search. A 2D array is a grid of rows and columns, read with two indexes and two nested loops. A fixed array has a set length; a list (Python list, Java ArrayList) can grow and shrink.

🎬 Step-by-step story

  1. Ten test scores in ten separate variables is messy. An array keeps them in one row of boxes under one name.
  2. Each box has an index. The first index is 0, so a 5-box array has indexes 0 to 4. scores[2] reads the third box.
  3. Traversal: a loop visits box 0, then 1, then 2 ... and adds each value to a running total.
  4. Algorithms on a row: keep the largest value seen so far, or search box by box until you find the target.
  5. A 2D array is a grid. grid[row][col] picks one cell. An outer loop walks the rows, an inner loop walks the columns.
  6. Your turn: pick a target and an action, guess the result, then watch the loop check each box.

Tip: drag the 3D scene to turn it. Use two fingers to zoom.

🤔 Common doubts, cleared

Why does indexing start at 0 and not 1?

The index says how far a box is from the start. The first box is 0 steps away.

Why not just use separate variables?

With an array, one loop handles any number of values. Separate variables need new code for each one.

Why does a[length] crash?

The last box is length − 1. a[length] points past the end.

Why start the maximum with a[0], not 0?

If all values are negative, 0 is bigger than all of them and would be a wrong answer.

In g[r][c], which comes first?

Row first, then column, like "row C, seat 7".

What happens when the search target is missing?

The loop checks every box, finds no match and returns −1.

What is an array?

An array stores many values of the same kind under one name. Think of a row of lockers with numbers on them.

Python:  scores = [72, 85, 90, 64, 78]
Java:    int[] scores = {72, 85, 90, 64, 78};
C++:     int scores[5] = {72, 85, 90, 64, 78};

Read one element: scores[1] gives 85. Change one: scores[3] = 70. Asking for scores[5] is an error (index out of bounds) because there is no sixth box.

In Java, a new array of numbers starts filled with 0; in C++ a local array is not cleared, so give it values first.

Traversing an array with a loop

Traversal means visiting every element once, in order. A loop does it, so the same code works for 5 values or 5,000. That is why lists help us generalise a solution.

Python:  for i in range(len(a)): print(a[i])
Java:    for (int i = 0; i < a.length; i++) { ... }
         for (int x : a) { ... }      // enhanced for
C++:     for (int i = 0; i < n; i++) { ... }

Use i < length, not i <= length, or you step one box past the end. The enhanced for (for-each) reads values but cannot change the array's boxes.

Standard array algorithms

Most array programs are built from a few patterns:

big = a[0]
for x in a:
    if x > big: big = x

2D arrays: rows and columns

A 2D array is an array of rows. grid[r][c] is the cell in row r, column c (both from 0).

Java:   int[][] g = new int[3][4];   // 3 rows, 4 columns
        g.length = 3, g[0].length = 4
Python: g = [[1, 2, 3], [4, 5, 6]]

Row-major traversal: outer loop over rows, inner loop over columns. Column-major: outer loop over columns. Typical tasks: row totals, column totals, largest in the grid, count matching cells, search a cell.

Arrays, lists and other structures compared

ArrayList (ArrayList, Python list)
SizeFixed when createdGrows and shrinks
Add/removeNot possible, make a new arrayadd, insert, remove
Reach item iVery fastVery fast
Lengtha.length (Java)list.size() / len(list)

Java's ArrayList stores objects only, so numbers go in as wrapper classes: Integer for int, Double for double. Java changes int to Integer for you (autoboxing) and back (unboxing). Removing items while looping forward skips the next item, so loop backwards when removing.

Other structures: a dictionary/map finds values by key, a set keeps unique items, a stack/queue controls the order you take items out.

Try it: your week of steps

Write down how many steps (or minutes of exercise) you did each day for 7 days. Put them in an array of length 7. By hand, run the loops: total, average, best day (index of the largest), and how many days were above 5,000. Then type it in any language and check your answers.

Key formulas and definitions

Worked examples

1. a = [4, 9, 2, 7]. Give a[0], a[3], the length and the last index.

a[0] = 4, a[3] = 7, length = 4, last index = 3.

2. Trace the sum loop on [5, 3, 8].

total = 0 → 5 → 8 → 16. Average = 16 / 3 ≈ 5.33.

3. Find the largest in [6, 11, 4, 11, 9] and its first index.

big = 6, then 11 (index 1). The second 11 is not bigger, so stays. Largest 11 at index 1.

4. Linear search for 7 in [3, 7, 1]. How many comparisons?

3 ≠ 7, 7 = 7 → found at index 1 after 2 comparisons.

5. g = [[1, 2, 3], [4, 5, 6]]. Give g[1][0], row totals and column totals.

g[1][0] = 4. Row totals 6 and 15. Column totals 5, 7, 9.

6. Reverse [1, 2, 3, 4, 5] in place.

Swap a[0]↔a[4], a[1]↔a[3]; the middle stays → [5, 4, 3, 2, 1]. Only n/2 = 2 swaps.

Common mistakes

Practice quiz

1. An array has 8 elements. Its last index is:
2. a = [10, 20, 30]. a[1] is:
3. Which loop visits every index of array a safely (Java)?
4. In g[2][3], the 2 is the:
5. Which can grow after it is made?

Practice: answer these yourself

Type or choose your answer, then press Check. Use a hint if you are stuck; the full solution appears after you answer.

Frequently asked questions

What is an array in simple words?

A row of numbered boxes with one name, each holding one value of the same type.

What is the difference between an array and a list?

An array has a fixed size. A list such as a Python list or Java ArrayList can grow and shrink.

What is a 2D array used for?

For tables and grids: seats, game boards, pixels, marks of students in many subjects.

Where this is taught

RomaniaClasa a VIII-aAlgorithms
RomaniaClasa a IX-aStoring data and organising code in a programming language
RomaniaClasa a X-aStructured data
RomaniaClasa a XI-aData structures
Ukraine8 класProblem solving
England (GCSE, A level)Year 103.2 Programming
USA (Common Core, NGSS, AP)Grade 9Algorithms and Programming
USA (Common Core, NGSS, AP)Grade 11Data Collections
USA (Common Core, NGSS, AP)Grade 11Algorithms and Programming
Russia8 классAlgorithms and programming
Russia9 классAlgorithms and programming
Russia9 классAlgorithms and programming

Learn first

Learn next

Related lessons

All Computer Science lessons