Write a program in C++ that reads integer values from standard input and writes to standard output the smallest of the inputs and the average input value.
The program should stop reading when a value equal to -1 or greater than 100 is encountered. It should also stop when an incorrect integer value (i.e., anything that isn't an int) is entered. If there is not an integer value in the input, the program should output "no integers provided"
#include<iostream>
#include<limits.h> // header file for the min function
using namespace std;
int main()
{
int n;
int sum=0,flag=0;
int i=0;
int smallest=INT_MAX; // this is for storing the smallest value
while(1) // the loop will terminate if the conditions underneath becomes valid
{
cin>>n;
if(n==-1 or n>100) //when -1 or a number greater than 100 is encountered , program stops
break;
if(cin.fail()) // if input is not a correct integer value this if body will execute
{
break;
}
flag=1;
smallest=min(smallest,n); // everytime smallest will be compared with the new input
// if new input is smaller then smallest will store the new input
sum+=n; // adding the new inputs for average calculation
++i; // this will tell the number of inputs
}
if(flag==0)
cout<<"no integer provided";
else
{
cout<<"smallest value "<<smallest<<endl;
cout<<"average "<<sum/i;
}
}
I have provided comments for better reference.
Point-> cin.fail() is used to valid the input . So if we get a wrong input or say which is not an integer value , then it will return true.
Get Answers For Free
Most questions answered within 1 hours.