How to Find Max and Min in Array C++ Program
How to find max and min in array C++ program.
In this article, you will learn how to find max and min in array C++ program.
Example
Enter the size of the array::
6
Enter the 6 elements of the array::
45 50 3 78 3 99
MIN SUM:: 179
MAX SUM:: 272
You should have knowledge of the following topics in c++ programming to understand these programs:
- C++
main()
function - C++
while
loop - C++ Data Type
Source Code
// How to Find Max and Min in Array C++ Program
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int s=0;
cout << "Enter the size of the array::\n";
cin >> s;
int arr[s];
cout << "\nEnter the " << s << " elements of the array::\n";
int i=0;
while (i<s) {
cin >> arr[i];
i++;
}
double min=INFINITY, max=-INFINITY;
int l=s, min_sum=0, max_sum=0, counter=0;
// It will get the lowest and highest value from the array
while (l--) {
if (arr[l] < min) {
min=arr[l];
}
if (arr[l] > max) {
max=arr[l];
}
if (arr[l]==arr[s-1]) {
counter++;
}
}
// It will calculate the minimum & maximum sum from the array
if (counter == s) {
l=s-1;
while (l--) {
min_sum += arr[l];
}
max_sum=min_sum;
} else {
l=s;
while (l--) {
if (arr[l]!=max) {
min_sum += arr[l];
}
if (arr[l]!=min) {
max_sum += arr[l];
}
}
}
// It will print the final output of the program
cout << "MIN SUM:: " << min_sum << endl;
cout << "MAX SUM:: " << max_sum << endl;
return 0;
}
Output
Enter the size of the array::
6
Enter the 6 elements of the array::
45 50 3 78 3 99
MIN SUM:: 179
MAX SUM:: 272
Explanation
In this given program, we have taken the input size of the array 6
and elements of the array 45 50 3 78 3 99
from the user. Then applied the standard calculation to find the minimum & maximum sum of the values from the given array.
Then It will return the minimum sum that is 179
and the maximum sum is 272
.