Find the Largest and Smallest Elements in a 1-D Array in C

This program finds the largest and smallest elements in a one-dimensional array by scanning through it once and keeping track of the current maximum and minimum.

C Program

#include <stdio.h>

int main() {
    int n, i;
    int arr[100];

    printf("Enter number of elements: ");
    scanf("%d", &n);

    printf("Enter %d elements: ", n);
    for (i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    int largest = arr[0];
    int smallest = arr[0];

    for (i = 1; i < n; i++) {
        if (arr[i] > largest) {
            largest = arr[i];
        }
        if (arr[i] < smallest) {
            smallest = arr[i];
        }
    }

    printf("Largest element: %d\n", largest);
    printf("Smallest element: %d\n", smallest);

    return 0;
}

Explanation

  • The array is read into memory first.
  • largest and smallest are both initialized to the first element.
  • A single loop from the second element onward compares each value: if it's bigger than the current largest, update largest; if it's smaller than smallest, update smallest.
  • This runs in a single pass — O(n) time — without needing to sort the array.

Sample Output

Enter number of elements: 5
Enter 5 elements: 12 45 3 67 22
Largest element: 67
Smallest element: 3

Leave a Comment