Skip to content
Devtoolry

Arrays and algorithms · beginner

C Program to Find the Largest Element in an Array

Find the largest element of an array in C with a loop, pass arrays to functions with their length, and find the second largest when the maximum repeats.

Finding the maximum is the "best so far" pattern: start with the first element and replace it whenever a bigger one appears. In C an array passed to a function decays to a pointer, so the function also needs the number of elements.

The program

C
#include <limits.h>
#include <stdio.h>

int largest(const int *a, int n) {
    int best = a[0];
    for (int i = 1; i < n; i++)
        if (a[i] > best)
            best = a[i];
    return best;
}

int main(void) {
    int numbers[] = {42, 7, 93, 18, 93, 64};
    int n = sizeof numbers / sizeof numbers[0];

    int max = largest(numbers, n);
    int second = INT_MIN;
    for (int i = 0; i < n; i++)
        if (numbers[i] < max && numbers[i] > second)
            second = numbers[i];

    printf("Largest: %d\nSecond largest: %d\n", max, second);
    return 0;
}
Output
Largest: 93
Second largest: 64

How it works

  1. sizeof numbers / sizeof numbers[0] gives the element count; it only works in the function where the array is declared.
  2. largest() starts with a[0] and keeps the bigger value at each step.
  3. For the second largest, only values strictly smaller than the maximum count, so the second 93 is ignored.
  4. INT_MIN from limits.h is the smallest int, a safe starting value.

Another way: Track both in one pass

Updating the largest and second largest together finds both in a single loop. When a new maximum appears, the old one becomes the second.

C
#include <limits.h>
#include <stdio.h>

int main(void) {
    int a[] = {-5, -2, -9, -2};
    int first = INT_MIN, second = INT_MIN;
    for (int i = 0; i < 4; i++) {
        if (a[i] > first) {
            second = first;
            first = a[i];
        } else if (a[i] < first && a[i] > second) {
            second = a[i];
        }
    }
    printf("%d %d\n", first, second);
    return 0;
}
Output
-2 -5

Common mistakes

  • Starting with best = 0, which is wrong for arrays of negative numbers.
  • Using sizeof inside the function: there the parameter is a pointer, so sizeof a / sizeof a[0] is 2 on a 64-bit system, not the array length.
  • Starting the loop at index 1 with best uninitialized instead of a[0].

Try it yourself

  • Also return the index of the largest element.
  • Find the smallest and largest elements in one pass.

Open the program in the C Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.

Browse all 25 C examples, or write your own program in the online C Compiler.