Lesson 2 of 12

Scan, count, search, and compare

Distinguish values from positions and preserve the exact tie rule a problem asks for.

A traversal visits each active cell

Use i to identify the cell and a[i] for the value. In [5, 2, 7, 8], values at even indices are 5 and 7, while the even values are 2 and 8. Read the wording carefully before deciding which quantity to test.

A sum can be wider than one element: 1000 copies of 10⁹ total 10¹². Keep that total in long long. A count of matching values adds one per match and cannot exceed n. A simple full traversal performs n visits.

The comparison decides ties

For a nonempty list, start minIndex and maxIndex at 0, then inspect indices 1 through n − 1. Compare a[i] with the candidate value, not with the candidate index. This works for all-negative inputs.

Updating a maximum on > retains the first occurrence. Updating on >= retains the last occurrence. Neither rule is universally right: the output specification determines which one to use.

Search answers different questions

A linear search checks successive values and does not require sorted data. A first-occurrence search saves i and breaks; a last-occurrence search keeps updating; an occurrence count increments for every match; existence only needs a bool.

Use −1 as a not-found marker because it cannot be a valid index. Never access a[answer] until you know answer is valid. If you need a one-based position, preserve the not-found marker rather than blindly adding one to −1.

C++23
#include <iostream>

int main() {
    int a[1000]{};
    int n = 0;
    std::cin >> n;
    for (int i = 0; i < n; ++i) { std::cin >> a[i]; }
    int target = 0;
    std::cin >> target;
    int first = -1;
    for (int i = 0; i < n; ++i) {
        if (a[i] == target) {
            first = i;
            break;
        }
    }
    std::cout << first << '\n';
    return 0;
}

When a second pass is the right tool

To count values above the final average, first store the list and calculate its sum; then revisit each value. The average is not yet known when the first value arrives.

For n > 0, a[i] > sum / n is mathematically equivalent to a[i] × n > sum, but integer division would truncate the first version. Under n ≤ 1000 and |a[i]| ≤ 10⁹, use 1LL * a[i] * n > sum for an exact, safe comparison. Two passes still perform work proportional to n.

Pause & predict

For [6, 9, 9, 4], a maximum-index scan updates on >=. Which zero-based index remains?

Choose an answer
Try it yourself

Turn the idea into code

Read 1 ≤ n ≤ 1000 values in [−10⁹, 10⁹]. Count those strictly above their final average. Include tests with all equal and negative values.

Give me a hint

Avoid dividing: multiply the candidate by the positive n using wide arithmetic.

Show the explained solution

The first pass computes the total and stores the values. The second applies the equivalent exact comparison. For [−10, −4, −4], the average is −6 and the answer is 2.

C++23
#include <iostream>

int main() {
    int a[1000]{};
    int n = 0;
    std::cin >> n;
    long long sum = 0;
    for (int i = 0; i < n; ++i) {
        std::cin >> a[i];
        sum += a[i];
    }
    int count = 0;
    for (int i = 0; i < n; ++i) {
        if (1LL * a[i] * n > sum) { ++count; }
    }
    std::cout << count << '\n';
    return 0;
}

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.