Solved

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

Posted on 2006-11-23
10
301 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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

743 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

11 Experts available now in Live!

Get 1:1 Help Now