In: Computer Science
- Write a function with no input parameter which keeps asking the user to enter positive numbers until the user enters an invalid input. (An invalid input is an input which includes at least one alphabet, like 123d4). The program should print the Max and Min of the numbers the user had entered as well as the distance between the Max and Min. (Remember to calculate the absolute distance). The function does not return anything
// Online C++ compiler to run C++ program online
#include <iostream>
#include <climits>
using namespace std;
void findMinMaxAbsolute(){
//variables to store min, max and difference
//min is set to maximum int value so as to get smaller value
//max is set to minimum int value so as to get larger value
//comparision
int min = INT_MAX,max = INT_MIN,diff=0;
//input variable
int n;
while(true){
cout<<"enter positive number:";
cin>>n;
//check if input is int or not
if(!cin){
cout<<"Closing as prev input was invalid";
cin.clear();
cin.ignore();
break;
}
//check for max value
if(n>max){
max = n;
}
//check for min value
if(n<min){
min = n;
}
}
//minimum value
cout<<"\nMin: "<<min<<endl;
//maximum value
cout<<"Max: "<<max<<endl;
//Absolute difference
cout<<"Difference between max and min is: "<<abs(max-min)<<endl;
}
//main function
int main() {
//call findMinMaxAbsolute function
findMinMaxAbsolute();
return 0;
}
Output: