Solved

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

Posted on 2006-11-23
10
307 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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
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

[Live Webinar] The Cloud Skills Gap

As Cloud technologies come of age, business leaders grapple with the impact it has on their team's skills and the gap associated with the use of a cloud platform.

Join experts from 451 Research and Concerto Cloud Services on July 27th where we will examine fact and fiction.

Question has a verified solution.

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

What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
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 user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

617 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