how do you find the minimum and maximum number from a given set of numbers without sorting them

?

i have the code but the it isnt working properly

#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
    const int SZ = 7;
    double sales[SZ];
    int x;
    double lowest = 0;
    double highest = 0;
   for(x = 0; x < SZ; x++)
    {
        cout<<"Enter sales for day "<<(x + 1)<<" >> ";
        cin>>sales[x];

    }
    cout<<"The entered sales are: ";
    for(x = 0; x< SZ; x++) {
     cout<<sales[x]<<"  ";
    }

     for ( int x = 0; x < SZ; x++ ) {
         if ( sales[x] > highest ) {
           highest = sales[x];
         }


     }
     for ( int x = 0; x < SZ; x++ ) {


        if( sales[x] < lowest ) {
        lowest = sales[x];
        }

     }
     cout<<"\nThe lowest sale is "<<lowest<<endl;
     cout<<"\nThe highest sale is "<<highest<<endl;


      getch();
     }

the highest number is working fine the lowest number im getting errors on it

it shows a weird number please help

// Line added here
lowest=sales[0];
for ( int x = 0; x < SZ; x++ ) {
  if( sales[x] < lowest ) {
    lowest = sales[x];
  }
}

Your "lowest" variable needs to be initialized to the first element in the array, else you will always have a problem when your lowest value is greater that 0.

Same also applies to how you find the highest value in the array, if the largest value is less than 0, you will always get 0.

Also you can combine the two loops in to one and just do both the checks in the same loop

Make two variables, one for min and one for max. Assign them to the first two numbers in your sequence. Compare each new element that you encounter with the min and the max. If it is larger than the max or smaller than the min, assign it. When you have looped through the list, you have the min and max.

This article has been dead for over six months. Start a new discussion instead.