Find minimum maximum element CPP
To find the minimum and maximum elements in an array in C++, you can use the following steps:
- Initialize two variables,
minElement
andmaxElement
, with the first element of the array. - Iterate through the array, starting from the second element.
- For each element, compare it with the current
minElement
andmaxElement
. - If the element is smaller than
minElement
, updateminElement
with the current element. - If the element is larger than
maxElement
, updatemaxElement
with the current element. - Continue iterating until all elements of the array have been processed.
- After the iteration,
minElement
will contain the minimum element in the array, andmaxElement
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.