Solved

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

Posted on 2006-11-23
10
303 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
Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

 
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
 
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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
returning a dereferenced pts in C++ 10 149
Grammars for C C++ and java 1 122
How to split this in C++ 4 101
How to Correctly derive class from CWinThread in MFC 4 35
IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

808 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