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;
#include <iostream>
usingnamespace 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;
}
elseif ( max < num )
{
max = num;
}
elseif ( 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;
}
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.