BlyxDocumentation
Browse chapters
Documentation / Numerical programming

Scan a vector for its maximum

Design a loop that finds the largest value even when every reading is negative.

Define the input

Finding a maximum requires at least one reading. This example supplies a nonempty literal. A reusable function should check len(readings) before indexing, or document and enforce the nonempty requirement at its call site.

Choose a starting value

Initialize peak from the first reading and begin the loop at index 1. Starting at zero as a candidate maximum would report a nonexistent zero for an all-negative input. The first real reading is a candidate you know belongs to the data.

Maintain a fact after every pass

Before reading index i, peak is the largest of the first i elements. Compare the next reading with peak, keep the larger value and increment i. The same fact now covers one more element. When i equals len(readings), the fact covers the whole input.

Estimate the cost

For n nonempty readings this scan performs n − 1 comparisons and stores a fixed number of local values beyond the input. A one-element vector skips the loop and returns its only element. Equal maxima do not change the reported value.

Try the program

Output Ready
Expected output
-1
Open in the full playground →

Practice

Try a vector containing just -12.0. Decide whether the loop body will run.

Hint

After initialization the index and the vector length both equal one.

Worked solution

The condition is false before the first pass. The initial reading is already the maximum.

Find

[-8.0, -1.0, -3.0]

Replace with

[-12.0]

Output after the change

-12