Find Maximum and Minimum elements in an Array

Finding the maximum and minimum values in an array is a fundamental operation in programming, often encountered when analyzing data. In this tutorial, we’ll explore how to accomplish this task using straightforward code examples.


#include <stdio.h>

int main() {
    // Declare an integer array
    int numbers[] = {10, 5, 20, 8, 15};

    // Calculate the number of elements in the array
    int count = sizeof(numbers) / sizeof(numbers[0]);

    // Initialize variables to store the maximum and minimum values
    int max = numbers[0]; // Assume the first element is the maximum
    int min = numbers[0]; // Assume the first element is the minimum

    // Loop through the array to find the maximum and minimum values
    for (int i = 1; i < count; i++) {
        // Check if the current element is greater than the current maximum
        if (numbers[i] > max) {
            max = numbers[i]; // Update the maximum value
        }

        // Check if the current element is smaller than the current minimum
        if (numbers[i] < min) {
            min = numbers[i]; // Update the minimum value
        }
    }

    // Display the maximum and minimum values
    printf("Maximum element in the array: %d\n", max);
    printf("Minimum element in the array: %d\n", min);

    return 0;
}

Here’s how the program works:

  1. We declare an integer array called numbers and initialize it with some values.
  2. We initialize two variables, max and min, to store the maximum and minimum values, respectively. We assume that the first element in the array is both the maximum and minimum initially.
  3. We use a for loop to iterate through the array starting from the second element (index 1). We skipped the element at index 0 since we’ve already assumed that the first element is the maximum and minimum.
  4. Inside the loop, we compare each element with the current maximum and minimum values.
    • If an element is greater than the current maximum, we update the max variable.
    • If it’s smaller than the current minimum, we update the min variable.
  5. Finally, we display the maximum and minimum values found in the array.