Simvik

Fix: the maximum is always the last reading

A semicolon after an if condition turns the update into a statement that always runs. An easy embedded C problem (Decisions and loops), run and graded in the…

easy · Decisions and loops · find-the-bug · if · syntax

Bug report. max_reading(v, n) should return the largest of n readings (n is at least 1). It returns the last reading every time. Fix it by changing one line.

Starter code

int max_reading(const int *v, int n) {
  int max = v[0];
  for (int i = 1; i < n; i++)
    if (v[i] > max);
      max = v[i];
  return max;
}

Example tests

The largest is in the middle

int v[] = { 3, 9, 4 };
printf("%d\n", max_reading(v, 3));

Expected output:

9

Learn it first

  • Decisions and loops · Choosing with if and switch, repeating with while and for, and the loop that never ends.

More Decisions and loops problems