Max and min of numbers input by the user

I am trying ti write a program that displays the maximum and the minimum of different numbers input by the user. I got the max part right but something seems wrong with my minimum. here is my code.

#include<iostream>

using namespace std;

int main()
{
int num,max = 0,min = 0;
char choice;
do
{
cout <<"Enter a number: ";
cin >> num;

cout <<"Do you want to continue?: ";
cin >> choice;

if(max < num)
max = num;
else if(min > num)
min = num;
}while(choice == 'y');

cout <<"The maximum is "<< max << endl;
cout <<"The minimum is "<< min << endl;

cin.ignore();
cin.get();

return 0;
}

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()
{
   bool empty = true;
   int max, min;

   char choice;
   do
   {
      cout << "Enter a number: ";
   
      int num;
      cin >> num;

      if ( empty )
      {
         empty = false;
         min = num;
         max = num;
      }
      else if ( max < num )
      {
         max = num;
      }
      else if ( num < min )
      {
         min = num;
      }

      cout << "Do you want to continue?: ";
      cin >> choice;
   } while ( choice == 'y' || choice == 'Y' );

   if ( !empty )
   {
      cout << "The maximum is " << max << endl;
      cout << "The minimum  is " << min  << endl;
   }

   cin.ignore();
   cin.get();

   return 0;
}
thanks can you explain the usage of bool empty???
It is the professor who will explain you. As for me I will say simply do at least something yourself.
I am learning C++ by myself, there is no professor around me unfortunately I showed you what I did though.
The problem with your code is that you initialised min with 0 , and zero is always smaller than any positive number so as long as you input any positive number (0 < num) will evaluate to true.
A rather cheap way to make your logic work is to initialize you min with ( (1 << sizeof(int)*4) - 1 ) .On a typical 32-bit system it will evaluate to (1 << 16) i.e. 2 tothe 16 - 1.
Better yet use vlad ' s way which checks whether you are inputing the first time.
Hope that helps.
Last edited on
"empty" means no input from user.

I am the professor, yeah :D
Last edited on
If you want to compare the numbers continuously, but not in pair, just remove the condition in the else branch.

1
2
3
4
if(max < num)
max = num;
else // if(min > num)
min = num;
Topic archived. No new replies allowed.