Program : Compute the maximum and minimum values in a 1-D array in C++.
Solution :
#include <iostream> using namespace std; int main() { const int size = 5; // Change the size to fit your array int arr[size], i, max, min; cout << "Enter " << size << " elements of an array:\n"; for (int i = 0; i < size; i++) { cin >> arr[i]; } max = arr[0]; min = arr[0]; for (i = 1; i < size; i++) { if (arr[i] > max) { max = arr[i]; } if (arr[i] < min) { min = arr[i]; } } cout << "Maximum value: " << max << endl; cout << "Minimum value: " << min << endl; return 0; }
Output :
Enter 5 elements of an array: 10 12 33 4 35 Maximum value: 35 Minimum value: 4
Dry Run :
max is arr[0] i.e. 10.
min is arr[0] i.e. 10.
i | i<size | arr[i] | arr[i]>max | max=arr[i] | arr[i]<min | min=arr[i] | i++ |
1 | True | arr[1]=12 | True | 10 | False | ——– | 2 |
2 | True | arr[2]=33 | True | 33 | False | ——– | 3 |
3 | True | arr[3]=4 | False | ——– | True | 4 | 4 |
4 | True | arr[4]=35 | True | 35 | False | ——– | 5 |
5 | False | ——– | ——– | ——– | ——– | ——– | — |
So, from the above table, final value of max is 35 and min is 4.
Want to practice more problems involving Array 1-D ? Click here.
2 comments
Way cool! Some extremely valid points! I appreciate you penning this post and the rest
of the website is extremely good.
I am in fact happy to glance at this blog posts which consists of tons
of useful data, thanks for providing these information.