C++ Program to Find the Maximum and Minimum in an Array

11/06/2024 0 By indiafreenotes

Finding the maximum and minimum elements in an array is a common problem in programming.

Let’s start by outlining the steps to find the maximum and minimum elements in an array:

  1. Initialize two variables, max and min, to represent the maximum and minimum elements, respectively.
  2. Iterate through the array elements.
  3. For each element, compare it with the current maximum and minimum values.
  4. Update the maximum and minimum values if necessary.
  5. After iterating through all elements, max and min will hold the maximum and minimum elements of the array, respectively.

Here’s how we can implement this in C++:

#include <iostream>

#include <climits> // for INT_MAX and INT_MIN

using namespace std;

// Function to find the maximum and minimum elements in an array

void findMaxMin(int arr[], int size, int& max, int& min) {

    max = INT_MIN; // Initialize max to the smallest possible integer value

    min = INT_MAX; // Initialize min to the largest possible integer value

    // Iterate through the array elements

    for (int i = 0; i < size; ++i) {

        // Update max if the current element is greater

        if (arr[i] > max) {

            max = arr[i];

        }

        // Update min if the current element is smaller

        if (arr[i] < min) {

            min = arr[i];

        }

    }

}

int main() {

    int arr[] = {3, 5, 2, 7, 9, 1, 4}; // Sample array

    int size = sizeof(arr) / sizeof(arr[0]); // Calculate the size of the array

    int max, min; // Variables to store the maximum and minimum elements

    // Find the maximum and minimum elements in the array

    findMaxMin(arr, size, max, min);

    // Print the maximum and minimum elements

    cout << “Maximum element: ” << max << endl;

    cout << “Minimum element: ” << min << endl;

    return 0;

}

In this code:

  • We define a function findMaxMin that takes an array arr, its size size, and two references to integers max and min.
  • We initialize max to the smallest possible integer value using INT_MIN and min to the largest possible integer value using INT_MAX.
  • We iterate through each element of the array and update max and min accordingly.
  • In the main function, we initialize a sample array, call findMaxMin to find the maximum and minimum elements, and then print the results.