All lessons

6. Arrays

Traversing and searching arrays

0 of 5 activities0%

Reading 1

Walk every element

Open

Most array work is a loop from 0 to size - 1. Keep a running total for sums, or track the best value so far for min/max.

To search, compare each element to a target and remember whether you found it (or at which index).

Stay inside bounds: valid indexes are 0 through size - 1.

int sum = 0;
for (int i = 0; i < n; i++) {
    sum += a[i];
}

int best = a[0];
for (int i = 1; i < n; i++) {
    if (a[i] > best) best = a[i];
}

Check 2

Safe loop

Open

For an array of n elements, which loop visits every index once?

Fill in 3

Last index

Open

In an array of length n, the last valid index is

Try it 4

Find the max

Open

Change the array values and rerun.

main.cpp
Loading editor…
Output will appear here.

Assignment 5

Count positives

Open

Read n (1 <= n <= 20), then read n integers into an array. Print how many of them are greater than 0.

main.cpp
Loading editor…