algoritmauzmanı
Sign in
TREN
2.1Array Operations
Lesson 2.1.2

Traversing an array

To print every element of an array, add them up or look for a value, you have to visit the elements one by one. This is called . In an array it is done with a counter: the starts at 0 and goes up by one on each pass.

What you will learn
  • Why the loop starts at 0 and ends at size - 1
  • How the same loop prints the elements and adds them up
  • Why traversal takes time
4 minTime O(n)Memory O(1)C · Java · Python
Know these first:2.1.1 Creating an array

1Idea

The filled cells run from 0 to size - 1. The loop starts with i = 0, handles arr[i] while i < size and increases i by one. When i reaches size, the loop ends. If the array is empty, size is 0 and the loop never runs; no separate check is needed.

On every pass you go straight to arr[i]: its address is computed from the start address of the array. When traversing a linked list, the place of the next node is only known from the field of the node you are on.

The same loop pattern serves other jobs too. Only the body of the loop changes. For example, the sum of the elements:

int sum(int arr[], int size) {    int result = 0;    for (int i = 0; i < size; i++)        result += arr[i];    return result;}

In Python you can also write for x in arr[:size]. But the slice arr[:size] builds a new list; traversing by index uses no extra memory.

2Step by step

The drawing prints the array holding 12, 7, 3 and 9. The capacity is 8 and size is 4. Green cells have already been printed.

01234567127394sizei
  1. i = 0. 0 < 4 is true: arr[0], which is 12, is printed. Output: 12
  2. i = 1: 7 is printed. Output: 12 7
  3. i = 2: 3 is printed. Output: 12 7 3
  4. i = 3: 9 is printed. Output: 12 7 3 9
  5. i = 4. 4 < 4 is false, so the loop ends and a newline is printed. Cells 4 to 7 were never looked at.

#define CAPACITY 8 void print(int arr[], int size) {    for (int i = 0; i < size; i++)    // only the filled part        printf("%d ", arr[i]);    printf("\n");}
static final int CAPACITY = 8; void print(int[] arr, int size) {    for (int i = 0; i < size; i++)    // only the filled part        System.out.print(arr[i] + " ");    System.out.println();}
CAPACITY = 8 def print_array(arr, size):    for i in range(size):  # only the filled part        print(arr[i], end=" ")    print()

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(n)

The loop runs size times and each pass does a fixed amount of work. n steps for n elements.

Memory
O(1)

Only the loop counter is used.

Reaching one element is ; traversal does that n times. Traversing a linked list is O(n) too, but an array usually finishes faster in practice because its elements sit side by side.

4Common mistake

A common mistake is writing the loop condition with <=:

for (int i = 0; i <= size; i++)    printf("%d ", arr[i]);   // arr[size] is not filled

The last pass reads arr[size]. That cell is either empty or, if the array is full, outside the array. C allows it and prints a random value; Java throws ArrayIndexOutOfBoundsException, and Python raises IndexError if the array is full. The last valid index is size - 1, so the condition must be i < size.

5Try it

How many times does the print loop run on an array with capacity 8 and size 5?

Show the answer

The answer is B. The loop runs while i < size: i takes the values 0, 1, 2, 3 and 4. Empty cells are not visited.

Do you have to traverse the array to read its 4th element?

Show the answer

The answer is B. In an array the address of each element is computed from its index; the 4th element is arr[3] and is read in time. Traversal is for when you need to visit every element.

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.