C bootcamp · Lab 08

Maximum in an array

mediumArrays12 minLesson: C Arrays

Read the question, write C on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

The first number is n, the length of a list. The next n numbers are the list.

Print the largest value in the list.

Input. Line 1: n. Line 2: n integers.

Output. One integer — the maximum.

Constraints

  • 1 ≤ n ≤ 100
  • Each value is between -1000 and 1000.

Examples

Example 1
Input
5
3 1 8 2 4
Output
8
Example 2 — A list of one item is already the max.
Input
1
42
Output
42
Hint
  1. Read n, then loop n times with scanf("%d", &nums[i]).
  2. Start max at nums[0], then walk the rest of the array.
Show correct code

Peek only after you have tried. You can still Check your own version.

#include <stdio.h>

int main(void) {
  int n;
  int nums[100];
  if (scanf("%d", &n) != 1 || n < 1 || n > 100) {
    return 1;
  }
  for (int i = 0; i < n; i++) {
    scanf("%d", &nums[i]);
  }
  int max = nums[0];
  for (int i = 1; i < n; i++) {
    if (nums[i] > max) max = nums[i];
  }
  printf("%d\n", max);
  return 0;
}
main.cC17 · gcc · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.