I'm writing a program that prompts the user to enter integer numbers.
The program stops reading when user inputs 0.
It should output the max and min element among inputed numbers.
I must write it without using arrays.
Input: 1 2 3 4 5 0
Output: min=1 max=5
My code:
#include <iostream>
using namespace std;
int main()
{
int n,max,min;
min=0;
max=0;
do{
cin>>n;
if(n>max){
max=n;
}
if(n<min){
min=n;
}
}
while(n!=0);
cout<<max<<endl;
cout<<min;
}
The problem is that when I enter the integers from my example the output is min=0 max=5, instead of min=1 max=5.
How can I fix it?
<limits>would have what you want for the 'set min to the highest possible' and vice versa. Better yet, I'd just treat the first input as a special case and assign its value to both max and min. The comparison only matters in the context of the inputs provided.min = max = nfor the first input, then the you want to check for zero before checkingminandmaxonlinegdb.com/rkdcqUFfuminandmax, then start the loop.