Learning pathOriginal reference
Lesson 4 of 12

Array helpers need a contract

Pass an active length, protect read-only inputs, and define missing results and tie rules.

The array does not carry n into the helper

A built-in parameter written int a[] is adjusted to a pointer parameter. It gives access to the caller’s elements rather than copying the whole array. It does not preserve the active length; pass n explicitly. Even int a[1000] in a parameter does not check the caller’s capacity.

The caller must guarantee valid accessible elements for indices 0 through n − 1. sizeof(a) inside this helper does not recover the caller’s array length. Use const int a[] for read-only access and int a[] when changing the elements is intentional.

Choose empty and missing behavior

A sum can naturally return zero for an empty input. A maximum that starts from a[0] needs n ≥ 1. Do not invent a zero initial maximum for a task that may contain only negative values.

A search helper can return the first zero-based index or −1 when absent. Return failure after the loop, once every candidate has been checked. The caller must check −1 before using the result as an index.

C++23
// Complete C++23 program. No input; output: 1 -1
#include <iostream>
int firstIndex(const int a[], int n, int target) {
    for (int i = 0; i < n; ++i) {
        if (a[i] == target) return i;
    }
    return -1;
}
int main() {
    int a[]{4, 6, 4, 8, 6};
    std::cout << firstIndex(a, 5, 6) << ' '
              << firstIndex(a, 5, 9) << '\n';
}

Test the promise, not just the sample

For search, test first position, last position, duplicates, and an absent target. For a sum, include empty, one-element, all-negative, and wide-total cases. For an in-place modifier, inspect the caller’s array afterward.

For the first minimum, initialize the best position to zero and replace it only for a strictly smaller value. Using ≤ replaces an earlier minimum on a tie. A scan takes O(n) time and only O(1) auxiliary space beyond the supplied array.

Value or reference?

The helper executes x += 10. Compare the caller’s value before and after the call.

Caller before5
Inside helper15
Caller after5

The parameter is a copy. Changing it leaves the caller’s variable untouched.

Guided simulation · Change the inputs to test your understanding.

Pause & predict

An array helper receives n = 3, but the caller allocated 1000 cells. Which indices belong to its promised active input?

Choose an answer
Try it yourself

Turn the idea into code

Return the first zero-based index of the minimum in a nonempty array. Input: 1 ≤ n ≤ 1000, then n integers in [−10⁹, 10⁹]. For 7 −2 −2 9, return 1.

Give me a hint

Keep a best index, initialized from a real element. Replace it only when a strictly smaller value appears.

Show the explained solution

After each visited index, best points to the earliest minimum of that prefix. Strict comparison preserves the earlier index on equality. The helper is O(n) time and O(1) auxiliary space.

C++23
// Complete C++23 program. Input: n, then n integers; 1 <= n <= 1000.
#include <iostream>
int indexOfMinimum(const int a[], int n) {
    int best = 0;
    for (int i = 1; i < n; ++i) {
        if (a[i] < a[best]) best = i;
    }
    return best;
}
int main() {
    int a[1000]{};
    int n = 0;
    std::cin >> n;
    for (int i = 0; i < n; ++i) std::cin >> a[i];
    std::cout << indexOfMinimum(a, n) << '\n';
}

Your notes

Ready for the next idea?

Mark complete when you can explain it yourself.

From a problem to a programIdentify the input, output, and constraints, then translate a small plan into C++.Variables, types, and remembered valuesChoose a representation, initialize it, and understand what assignment really changes.Arithmetic without surprisesPredict division and remainder, widen before multiplication, and format decimal answers.Conditions and logical decisionsBuild exclusive categories, combine comparisons, and protect operations with short-circuit logic.Optional: other ways to chooseRecognize switch for exact choices and the conditional operator for choosing a value.For loops: make repetition preciseTrace initialization, condition, body, and update—and avoid an extra iteration.While, do-while, and stopping rulesChoose a loop from its stopping condition and read the exact input format.Break, continue, and early answersDistinguish leaving a loop from skipping one iteration, without losing required input.Five patterns worth understandingUse sums, counts, best-so-far candidates, products, and flags to process a stream.Nested loops: rows and columnsTranslate a shape into two loop roles and count the total work.Take a number apart, one digit at a timeUse remainder and division to process decimal digits, including zero.Multiple cases and a debugging mindsetCombine the patterns, isolate each case, and test the boundaries that can break your idea.Arrays: give every value a placeUnderstand indices, initialization, capacity, active length, and the first safe array loop.Scan, count, search, and compareDistinguish values from positions and preserve the exact tie rule a problem asks for.Change a sequence without losing itUpdate, copy, compare, reverse, and inspect neighbours using the correct bounds.Matrices: think in two coordinatesTraverse tables, total rows and columns, inspect diagonals, and protect grid neighbours.Characters become stringsSeparate characters from numbers, then safely inspect and edit managed text.Read the text the problem actually givesChoose words or full lines, preserve empty cases, and reset only the state that needs it.Scan text: count, filter, transformBuild a result from matching characters without losing leading zeros or skipping shifted text.Join, compare, and find textLearn content comparison, lexicographical order, substring counts, and the not-found sentinel.