Solved

c++ comparing numbers in an array and printing the highest number

Posted on 2006-11-23
10
302 Views
Last Modified: 2008-01-09
Hello,

I am playing with c++ arrays and I need a little direction on how to start this program or what function to use to do the compare of the entries within an array so I can determine which number is the highest  or lowest in the list.  Just trying to figure out how to report on what is entered in an int array.  

Thanks in advance!
0
Comment
Question by:meaar
  • 5
  • 4
10 Comments
 

Author Comment

by:meaar
ID: 18005746
I found the example below, but for some reason the line, "cin >> numbers;" is giving errors.   I basically want the input to be put into an int numbers[] array.  Any ideas why?  Also, how do I print the last number in the array which should end up being the highest number?

----------------------------------------------------------------------

#include <stdlib.h>
#include <iostream.h>

const int MAXSIZE = 5;

void selectionSort ( int arr[], int size );
void swap ( int* x, int* y );

int main()
{
      int numbers[MAXSIZE];
      int index;

        cout << "Please enter 5 numbers" << endl;
        cin >> numbers;

      cout << "Numbers entered: ";
      for (index = 0; index < MAXSIZE; index++)
            cout << numbers[index] << " ";

      selectionSort(numbers, MAXSIZE); // perform sort routine

      for (index = 0; index < MAXSIZE; index++)
            cout << numbers[index] << " ";

        cout << endl << "The HIGHEST number in the list is: ";

      cout << endl << endl;
      system("PAUSE");
      return EXIT_SUCCESS;
}

// selection sort technique to sort array elements into ascending order
void selectionSort ( int arr[], int size )
{
    int indexOfMin, pass, j;

    for ( pass = 0; pass < size - 1; pass++ )
    {
            indexOfMin = pass;

            for ( j = pass + 1; j < size; j++ )
                if ( arr[j] < arr[indexOfMin] )
                    indexOfMin = j;

          if (indexOfMin != pass)
               swap ( &arr[pass], &arr[indexOfMin] );
    }
}

// interchanges values of two integer variables
void swap ( int* x, int* y )
{
    int temp;
    temp = *x;
    *x = *y;
    *y = temp;
}
0
 
LVL 86

Expert Comment

by:jkr
ID: 18005788
Try #include <stdlib.h>
#include <iostream>

using namespace std;

const int MAXSIZE = 5;

void selectionSort ( int arr[], int size );
void swap ( int* x, int* y );

int main()
{
      int numbers[MAXSIZE];
      int index;

       cout << "Please enter 5 numbers" << endl;
      for (index = 0; index < MAXSIZE; index++)
            cin >> numbers[index];


      cout << "Numbers entered: ";
      for (index = 0; index < MAXSIZE; index++)
            cout << numbers[index];

      selectionSort(numbers, MAXSIZE - 1); // perform sort routine

      for (index = 0; index < MAXSIZE; index++)
            cout << numbers[index] << " ";

       cout << endl << "The HIGHEST number in the list is: " << numbers[0];

      cout << endl << endl;
      system("PAUSE");
      return EXIT_SUCCESS;
}

// selection sort technique to sort array elements into ascending order
void selectionSort ( int arr[], int size )
{
    int indexOfMin, pass, j;

    for ( pass = 0; pass < size - 1; pass++ )
    {
            indexOfMin = pass;

            for ( j = pass + 1; j < size; j++ )
                if ( arr[j] < arr[indexOfMin] )
                    indexOfMin = j;

          if (indexOfMin != pass)
               swap ( &arr[pass], &arr[indexOfMin] );
    }
}

// interchanges values of two integer variables
void swap ( int* x, int* y )
{
    int temp;
    temp = *x;
    *x = *y;
    *y = temp;
}

that should work better.
0
 

Author Comment

by:meaar
ID: 18005797
HI jkr,

Quick response. :)  

There is something a little off.  Here's an example output:

Please enter 5 numbers
1 2 5 9 8
Numbers entered: 125981 2 5 9 8
The HIGHEST number in the list is: 1

Press any key to continue . . .
0
 
LVL 86

Expert Comment

by:jkr
ID: 18005854
That is odd. What compiler are you using?
0
 

Author Comment

by:meaar
ID: 18005861
old one: visual C++ 6.0. :(
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 86

Expert Comment

by:jkr
ID: 18005865
Never mind, just a missing '<< " ";' in the output and a wrong place to look for the maximum. Try

#include <stdlib.h>
#include <iostream>

using namespace std;

const int MAXSIZE = 5;

void selectionSort ( int arr[], int size );
void swap ( int* x, int* y );

int main()
{
      int numbers[MAXSIZE + 1];
      int index;


       cout << "Please enter 5 numbers" << endl;
      for (index = 0; index < MAXSIZE; index++)
           { cin >> numbers[index]; cout << numbers[index] << endl;}


      cout << "Numbers entered: ";
      for (index = 0; index < MAXSIZE; index++)
            cout << numbers[index] <<" " ;

      selectionSort(numbers, MAXSIZE - 1); // perform sort routine

      cout << "Numbers sorted: ";
      for (index = 0; index < MAXSIZE; index++)
            cout << numbers[index] << " ";

       cout << endl << "The HIGHEST number in the list is: " << numbers[MAXSIZE];

      cout << endl << endl;
      system("PAUSE");
      return EXIT_SUCCESS;
}

// selection sort technique to sort array elements into ascending order
void selectionSort ( int arr[], int size )
{
    int indexOfMin, pass, j;

    for ( pass = 0; pass < size - 1; pass++ )
    {
            indexOfMin = pass;

            for ( j = pass + 1; j < size; j++ )
                if ( arr[j] < arr[indexOfMin] )
                    indexOfMin = j;

          if (indexOfMin != pass)
               swap ( &arr[pass], &arr[indexOfMin] );
    }
}

// interchanges values of two integer variables
void swap ( int* x, int* y )
{
    int temp;
    temp = *x;
    *x = *y;
    *y = temp;
}
0
 
LVL 86

Accepted Solution

by:
jkr earned 350 total points
ID: 18005867
Ouch, make that

       cout << endl << "The HIGHEST number in the list is: " << numbers[MAXSIZE - 1];

0
 

Author Comment

by:meaar
ID: 18005930
Hi jkr,

For some reason I made the following changes and it seems to work.  I'll give you the points, but have a couple of quick questions.  I noticed that if I put  a character (example: a) it gives me the same number each time.   Also could you give me direction...  I want to read to find out what this means:

temp - *x;
*x = *y;
*y - temp;

What does the * do?

--------------------------------------------------------------

#include <stdlib.h>
#include <iostream>

using namespace std;

const int MAXSIZE = 5;

void selectionSort ( int arr[], int size );
void swap ( int* x, int* y );

int main()
{
      int numbers[MAXSIZE + 1];
      int index;


      cout << "Please enter 5 numbers" << endl;
      for (index = 0; index < MAXSIZE; index++)
           { cin >> numbers[index];}


      //cout << "Numbers entered: ";
      for (index = 0; index < MAXSIZE; index++)
           //cout << numbers[index] <<" " ;

      selectionSort(numbers, MAXSIZE); // perform sort routine

      //cout << "Numbers sorted: ";
      //for (index = 0; index < MAXSIZE; index++)
      //      cout << numbers[index] << " ";

      cout << endl << "The HIGHEST number in the list is: " << numbers[4];

      cout << endl << endl;
      system("PAUSE");
      return EXIT_SUCCESS;
}

// selection sort technique to sort array elements into ascending order
void selectionSort ( int arr[], int size )
{
    int indexOfMin, pass, j;

    for ( pass = 0; pass < size - 1; pass++ )
    {
            indexOfMin = pass;

            for ( j = pass + 1; j < size; j++ )
                if ( arr[j] < arr[indexOfMin] )
                    indexOfMin = j;

          if (indexOfMin != pass)
               swap ( &arr[pass], &arr[indexOfMin] );
    }
}

// interchanges values of two integer variables
void swap ( int* x, int* y )
{
    int temp;
    temp = *x;
    *x = *y;
    *y = temp;
}
0
 
LVL 39

Assisted Solution

by:itsmeandnobodyelse
itsmeandnobodyelse earned 150 total points
ID: 18007432
>>>> What does the * do?

The * is dereferencing a pointer. If dealing with pointers the pointer's value is the address of a variable in memory. To assign or access the value the pointer is pointing to - and not the address value - you need to dereference the pointer.

In your sample above pointers were not needed. You should turn the swap fuction to take references instead:

void swap ( int& x, int& y )
{
    int temp = x;
    x = y;
    y = temp;
}

A reference is safer than a pointer cause it always is a reference to a *valid* variable. A pointer can contain a  NULL address or some other invalid address.              

The call of the swap function would change as well to

    swap ( arr[pass], arr[indexOfMin] );


>>>> I noticed that if I put  a character (example: a)

I assume you mean "if you enter a 'a' instead of a digit" the program doesn't work correctly, yes?

That is why you read from cin into an integer variable (cin >> numbers[index];)  The >> operator isn't a standard C/C++ operator here but an overloded function like that:

   istream& operator<< (istream& is, int& i);

cin >> numbers[index]  will be turned by the compiler to a call to that function, i. e.

    cin = operator<<(cin, number[index]);

That function tries to convert the given input from keyboard to a valid integer. If you pass in a character 'a' the conversion fails and the cin istream was set to 'fail'. As long as you don't reset the cin fail bit no further read operation will succeed on cin. If you want to make your prog more robust you would need to read in a string - what rarely fails - and do the conversion to integer yourself, e. g.

// #include <stdlib.h>  // you don't need that normally
#include <string>
#include <iostream>
using namespace std;

   
     string input;
     for (index = 0; index < MAXSIZE; ++index)
     {
           cout << "Please enter a number ==> ";
           cin >> input;
           numbers[index] = atoi(input.c_str();
     }
     
Here, the atoi function simply ignores any characters. It would conver "a" to 0 and "123xyz" to 123.

You also could check for valid input and output an error message if wrong:

#include <sstream>
...


     string input;
     for (index = 0; index < MAXSIZE; ++index)
     {
           cout << "Please enter a number ==> ";
           cin >> input;
           istringstream iss(input);
           iss >> numbers[index];
           if (iss.fail())
           {
                // note, the istringstream fails same as cin would do, but that doesn't matter
                // cause we use a new istringstream object next time
                cout << "The input [" << input << "] is not a valid number. " << endl;
                index--;    // we decrement the loop counter to get the same index next time
                continue;
           }
           numbers[index] = atoi(input.c_str();
     }


Regards, Alex
0
 

Author Comment

by:meaar
ID: 18029456
Awesome answer Alex.  Thanks!
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Handling string inputs in C/Linux 23 179
c++ how to tell if the progra is ctl or mfc atl ect 6 64
Handle Exceptions during instantiation 28 411
C Language combined operators 28 106
In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

867 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

25 Experts available now in Live!

Get 1:1 Help Now