Calculating the min and max using a loop

I am writing code for an assignment that wants me to make a program that asks the user for the amount of integers they'd like to input then it accepts each input while testing if the value is the max value or the minimum.

The program runs fine but for some reason will stop and show me the min and max number when I have entered in 1 integer less than the original input.


For example,

- If I input 5 for the first value, it asks me to enter 5 integers.
- After entering 4 numbers, 1 2 3 and 4.
- It tells me the max is 4 and min is 1.
- It prevents me from entering in the 5th integer.

Additionally,
- If I input 5 for the first value, it asks me to enter 5 integers.
- If I enter a negative number, like -1, the input is further shortened.
- If I enter -1, 2, 3 then the output is min: 2 and max: 3


Any help is much appreciated!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
  #include <iostream>
using namespace std;

int main()
{
  int input;
  int tmp;
  int counter = 1;
  int max_num = 0;
  int min_num;

//prompt user for integer amount
  cout << "How many integers would you like to enter? " << endl;
  cin >> input;

  cout<< "Please enter " << input << " integers." << endl;

  tmp = input;

//loop for requested amount with a test for each input
  while (counter <= tmp){
  cin >> input;

//if smaller than previous number it is the minimum
  if (input < min_num || min_num == -1){
    min_num = input;
    counter++;
  }

// if larger than previous number it becomes max number else
  if (input > max_num){
    max_num = input;
    counter++;
  }

//continue loop if number isn't bigger than max or smaller than min
  else { counter++;
  }
}

//display the max and min
cout << "min: " << min_num << endl;
cout << "max: " << max_num << endl;

return 0;

}
Last edited on
Topic archived. No new replies allowed.