C Workshop · Array Maximum
Lesson C

Array Maximum

Walk the array once. Keep the largest value seen so far.

What it is

To find a maximum you walk the row once and remember the biggest value you have seen so far. You do not need to sort. One pass is enough.

Approach

  1. Read n and the first integer as mx.
  2. Loop the rest of the values.
  3. if (x > mx) mx = x.
  4. Print mx.

Where this is used in the real world

Diagram

1

mx=1

first

2

8>1

update

3

3>8?

no

4

5>8?

no

Run algorithm

Each step highlights the matching C line. Program output appears only when a line that prints actually runs.

Ready
C code
1#include <stdio.h>
2int main(void) {
3    int n, i, x, mx;
4    scanf("%d", &n);
5    scanf("%d", &mx);
6    for (i = 1; i < n; i++) {
7        scanf("%d", &x);
8        if (x > mx) mx = x;
9    }
10    printf("%d\n", mx);
11    return 0;
12}
What this line does
Press Run algorithm. The highlight will move through the C code.
Program output
(no output yet)

Check your understanding

Five questions. Pick one answer each, then Check answers. The correct choice turns green.

1. Sample max is:

8 is largest.

2. mx starts as:

Need a real starting value.

3. Update mx when:

Strictly greater.

4. This scan is:

Linear scan.

5. If the array were 2-D marks[students][subjects], max would use:

Nested for.