jeudi 26 janvier 2017

Finding the 2 greatest and smallest integers in a sequence

I am trying to make a program in class that will find the 2 largest and smallest integers in a given sequence and then print them to the user. A sample run would look something like this:

Enter the sequence size: 8
Enter the sequence: 5 8 9 12 -6 4 -8 10

The two smallest values are: -8 -6
The two largest values are: 12 10

I am not allowed to use sort or array. I've been at it all night but I can't seem to figure it out, could anyone point me in the right direction? This is where I'm currently stuck at - It wont compile because the 'small1' and 'large1' variables aren't initialized, however if I set them to zero they remain as zero in the sample run.

int small1, small2, large1, large2, loopcount, sequencevalue;
// Ask the user to enter the first number
cout << "Sequence Size: ";
cin >> loopcount;

// Enter the sequence and start the loop
cout << "\nEnter the Sequence: ";

for (int i = 0; i < loopcount; i++)
{
    cin >> sequencevalue;

    if (sequencevalue < small1)
    {
        small2 = small1;
        small1 = sequencevalue;
    }

    if (sequencevalue > large1)
    {
        large2 = large1;
        large1 = sequencevalue;
    }
}

// Small variables
if (small1 == 0)
{
    small1 = sequencevalue;
}
else
{
    if (sequencevalue < small1)
    {
        small2 = small1;
        small1 = sequencevalue;
    }
}

// Large variables
if (large1 == 0)
{
    large1 = sequencevalue;
}
else
{
    if (sequencevalue < large1)
    {
        large2 = large1;
        large1 = sequencevalue;
    }
}

// Final Output
cout << "Two smallest values: " << small1 << " " << small2 << "\n";
cout << "Two largest values: " << large2<< " " << large1 << "\n";

I greatly appreciate any assistance on this matter, thank you for your time.

Aucun commentaire:

Enregistrer un commentaire