Array Max & Min
Program to find maximum and minimum element in an array
BeginnerTopic: Array Programs
C++ Array Max & Min Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
#include <climits>
using namespace std;
int main() {
int n;
cout << "Enter number of elements: ";
cin >> n;
int arr[n];
cout << "Enter " << n << " elements: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int max = INT_MIN, min = INT_MAX;
for (int i = 0; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
}
cout << "Maximum element: " << max << endl;
cout << "Minimum element: " << min << endl;
return 0;
}Output
Enter number of elements: 5 Enter 5 elements: 10 5 20 15 8 Maximum element: 20 Minimum element: 5
Understanding Array Max & Min
This program finds the maximum and minimum elements in an array. We initialize max to INT_MIN (smallest possible int) and min to INT_MAX (largest possible int). We iterate through the array, updating max and min when we find larger or smaller values.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.