Solved

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

Posted on 2006-11-23
10
305 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Grammars for C C++ and java 1 138
IdTCPClient1->Disconnect(); not working 3 86
Dynamically allocate memory 9 70
Header Errors LNK2019, LNK1120 - Unresolved Externals 4 248
Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
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…
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.

735 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