Skip to content

Finding things in an array

Read · 1 of 4

Start from a real element

To find the biggest value, keep a "best so far" and update it as you walk the array. Start it at the first element, not at 0: if every number is negative, 0 would wrongly win.

To find where a value is, walk the array and stop at the first match. If you get to the end, it isn't there (by convention, report -1).

Read this lesson as text

Largest, smallest, position of a value, and how a wrong starting value breaks code.

Start from a real element

To find the biggest value, keep a "best so far" and update it as you walk the array. Start it at the first element, not at 0: if every number is negative, 0 would wrongly win.

To find where a value is, walk the array and stop at the first match. If you get to the end, it isn't there (by convention, report -1).

Break it: Break the maximum

This should print the biggest of n numbers. Find an input where it gets it wrong.

#include <stdio.h>

int main() {
    int n, x, best = 0;
    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &x);
        if (x > best) best = x;
    }
    printf("%d\n", best);
    return 0;
}

Input rules: first line n (1 to 20), second line n whole numbers between -1000 and 1000.

Exercise: Where is it?

Read n (1 to 100), n numbers, then a value x. Print the position (0-based) of the first x, or -1 if it isn't there.

Exercise: Second largest

Read n (2 to 100) and n numbers, all different. Print the second largest, in one pass over the array.