Find minimum maximum element CPP

To find the minimum and maximum elements in an array in C++, you can use the following steps:

  1. Initialize two variables, minElement and maxElement, with the first element of the array.
  2. Iterate through the array, starting from the second element.
  3. For each element, compare it with the current minElement and maxElement.
  4. If the element is smaller than minElement, update minElement with the current element.
  5. If the element is larger than maxElement, update maxElement with the current element.
  6. Continue iterating until all elements of the array have been processed.
  7. After the iteration, minElement will contain the minimum element in the array, and maxElement will contain the maximum element in the array.

Here is an example code snippet that demonstrates this approach:

#include <iostream>
using namespace std;

int main() {
    int arr[] = {5, 2, 9, 1, 7};
    int size = sizeof(arr) / sizeof(arr[0]);

    int minElement = arr[0];
    int maxElement = arr[0];

    for (int i = 1; i < size; i++) {
        if (arr[i] < minElement) {
            minElement = arr[i];
        }
        if (arr[i] > maxElement) {
            maxElement = arr[i];
        }
    }

    cout << "Minimum element: " << minElement << endl;
    cout << "Maximum element: " << maxElement << endl;

    return 0;
}

This code initializes minElement and maxElement with the first element of the array arr. Then, it iterates through the remaining elements of the array, comparing each element with the current minimum and maximum. If a smaller element is found, minElement is updated, and if a larger element is found, maxElement is updated. Finally, the minimum and maximum elements are printed to the console.