Logic error in code

I made a program that determines the largest and smallest integers in a list. The program works but displays the largest and smallest integers however many times they appear in the list. I've considered many possibilities but none seem to work.

Here is the code:

{
int num1, num2, num3, num4, num5;
cout << "Enter 5 integers:" << endl;
cin >> num1;
cin >> num2;
cin >> num3;
cin >> num4;
cin >> num5;

//Determine smallest integer.
if ( num1 <= num2 && num1 <= num3 && num1 <= num4 && num1 <= num5 )
{
cout << num1 << " is the smallest integer." << endl;
}
if ( num2 <= num1 && num2 <= num3 && num2 <= num4 && num2 <= num5 )
{
cout << num2 << " is the smallest integer." << endl;
}
if ( num3 <= num2 && num3 <= num1 && num3 <= num4 && num3 <= num5 )
{
cout << num3 << " is the smallest integer." << endl;
}
if ( num4 <= num2 && num4 <= num3 && num4 <= num1 && num4 <= num5 )
{
cout << num4 << " is the smallest integer." << endl;
}
if ( num5 <= num2 && num5 <= num3 && num5 <= num4 && num5 <= num1 )
{
cout << num5 << " is the smallest integer." << endl;
}

//Determine largest integer.
if ( num1 >= num2 && num1 >= num3 && num1 >= num4 && num1 >= num5 )
{
cout << num1 << " is the largest integer." << endl;
}
if ( num2 >= num1 && num2 >= num3 && num2 >= num4 && num2 >= num5 )
{
cout << num2 << " is the largest integer." << endl;
}
if ( num3 >= num2 && num3 >= num1 && num3 >= num4 && num3 >= num5 )
{
cout << num3 << " is the largest integer." << endl;
}
if ( num4 >= num2 && num4 >= num3 && num4 >= num1 && num4 >= num5 )
{
cout << num4 << " is the largest integer." << endl;
}
if ( num5 >= num2 && num5 >= num3 && num5 >= num4 && num5 >= num1 )
{
cout << num5 << " is the largest integer." << endl;
}

system ("pause");
return 0;

I get that there are better ways to write this but I just need a fix for the multiple output issue.
Have you considered using else-ifs?

1
2
3
4
5
6
7
8
9
if (condition) {
//Stuff
} 
else if (condition) {
//This stuff is only executed if the above if's stuff was not executed.
}
else if (condition) {
//This stuff is only executed if the above if's stuff and the above else if's stuff was not executed.
}


-Albatross
Topic archived. No new replies allowed.