2

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?

5
  • @Devolus can i do without it? Commented Feb 28, 2021 at 17:36
  • 2
    When you initialize min to 0 and you compare it against i.e. 5 then what happens? Similar, if you init max = 0 and you enter -1 what happens? Commented Feb 28, 2021 at 17:36
  • <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. Commented Feb 28, 2021 at 17:37
  • As @sweenish said, the best way is to set min = max = n for the first input, then the you want to check for zero before checking min and max onlinegdb.com/rkdcqUFfu Commented Feb 28, 2021 at 18:05
  • The trick is to input the first number, and assign to both min and max, then start the loop. Commented Feb 28, 2021 at 18:06

1 Answer 1

2

You may want to input a starting value first, then loop:

int main()
{
  int n, min, max;
  cin >> n;
  min = n;
  max = n;
  if (n != 0)
  {
    while (cin >> n)
    {
       if (n == 0) break;
       if (n > max) max = n;
       if (n < min) min = n;
    }
  }
  std::cout << "min: " << min << ", max: " << max << "\n";
  return 0;
}

In the code above, the first value is read and checked for 0. The program stops input if the value is zero.

The minimum and maximum are assigned the first value.

Then the loop starts.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.