Write the main() program in C that keeps reading real numbers from the standard
ID: 3906244 • Letter: W
Question
Write the main() program in C that keeps reading real numbers from the standard input and calls a MinMax() function to determine whether this number is the minimum or the maximum compared to all the numbers read so far. Then main() prints both the minimum and maximum numbers to the standard output. Then main() continues reading another real number and this process repeats until the EOF occurs.
Note: • The program should print a proper message if there are no inputs.
• The program should properly work if there is only one input.
Explanation / Answer
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts. Thanks
//Code
#include<stdio.h>
/*method to o determine whether number 'num' is the minimum or the maximum
*compared to all the numbers read so far
*here minMax is an array containing two elements, where minMax[0]
*is the current minimum number, and minMax[1] is the current maximum
*numEntries is the number of entries read so far
*/
void MinMax(float num,float *minMax, int numEntries){
if(numEntries==0){
//first entry, setting num as both minimum and maximum
minMax[0]=num;
minMax[1]=num;
printf("Current Minimum and Maximum is %f ",minMax[0]);
}else{
//subsequent entries, checking if the value is less than minimum
//or greater than maximum
if(num<minMax[0]){
//new minimum
minMax[0]=num;
}
if(num>minMax[1]){
//new maximum
minMax[1]=num;
}
//displaying current minimum and maximum
printf("Current Minimum: %f ",minMax[0]);
printf("Current Maximum: %f ",minMax[1]);
}
}
int main(){
//defining the array and other required variables
float minMax[2];
int numEntries=0;
float num=0;
//reading until EOF (press ctrl+Z to terminate)
while (scanf("%f", &num) == 1 && !feof(stdin)){
//checking and displaying current minimum and maximum
MinMax(num,minMax,numEntries);
numEntries++;
}
return 0;
}
/*OUTPUT*/
10
Current Minimum and Maximum is 10.000000
5
Current Minimum: 5.000000
Current Maximum: 10.000000
11
Current Minimum: 5.000000
Current Maximum: 11.000000
20
Current Minimum: 5.000000
Current Maximum: 20.000000
15
Current Minimum: 5.000000
Current Maximum: 20.000000
17
Current Minimum: 5.000000
Current Maximum: 20.000000
-20
Current Minimum: -20.000000
Current Maximum: 20.000000
72
Current Minimum: -20.000000
Current Maximum: 72.000000
66
Current Minimum: -20.000000
Current Maximum: 72.000000
^Z
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.