I'm working on a program that takes 5 integers from input and then prints out the smallest and second smallest of those integers. The program correctly outputs the smallest number but the program often outputs the second smallest number incorrectly because of ordering.
For example, if I enter 33, -6, -15, 0, and 12, the program will print -15 as the smallest and -6 as the second smallest. If however, I enter 3, 6, 7, 8, and 9, the program outputs 3 as the smallest and instead of outputting 6 as the second smallest, I get garbage for the second smallest. How can I fix this?
My Code:
#include <iostream>
using namespace std;
int main()
{
const int MAX_NUM_INTEGERS = 5;
int Integers[5];
int i = 0;
int Smallest_Value = INT_MAX;
int Second_Smallest_Value = 0;
while ( i < MAX_NUM_INTEGERS)
{
cout << "Enter an Integer : ";
cin >> Integers[i];
i++;
if (Integers[i-1] < Smallest_Value)
{
Second_Smallest_Value = Smallest_Value;
Smallest_Value = Integers[i-1];
}
}
cout << "The Smallest Integer Entered is: " << Smallest_Value << " and the Second Smallest is: " << Second_Smallest_Value << "\n";
return 0;
}