In: Computer Science
Write code that finds the largest number in data and stores it in the variable max and the smallest number in data and stores it in min.
Test Cases
Test case #1
Expected result: max is 52.66; min is 15.53
Test case #2
Expected result: max is 56.95; min is 5.77
Test case #3
Expected result: max is 77.02; min is 24.24
Test case #4
Expected result: max is 90.48; min is 35.94.
Given, An array having some elements and we have to find the maximum of all the elements in that array and also the minimum of all elements and storing their corresponding value in max and min.
We will first apply a simple logic to store maximum of all elements in the given data (array). Similarly further by doing one change, we can also find the minimum of all elements. Let's see the same in following steps:
1. Create a variable max_ele and store the value 0.0 initially in it.
2. Traverse through the array and compare the next element each time whether it is greater than max_ele or not, and if it is, then simply assign that value of element in our max_ele variable.
3. Repeat the same process again for all elements of array and finally we'll be having our maximum element in that array.
4. Print the max_ele out of the loop.
Above Process is same for minimum also, just change the variable to min_ele and store any big value i.e 32768.0. Also, each time compare whether each element is smaller or not and if it is, store the same in min_ele and print the min_ele.
The following code is in C++ language.
Example : A = {46.87, 32.54, 52.66, 15.53}
#include <iostream>
using namespace std;
int main(void){
double A[] = {46.87, 32.54, 52.66, 15.53};
double max_ele = 0.0, min_ele = 329484.0;
for(int i=0; i<4; i++){
if(A[i] > max_ele) max_ele = A[i];
if(A[i] < min_ele) min_ele = A[i];
}
cout << "max is " << max_ele << "\n";
cout << "min is " << min_ele ;
return 0;
}
Output : max is 52.66; min is 15.53.
Same is for all other test cases also. Hope you understand. Thank You !