user1386320
user1386320

Reputation:

Get the maximum number from an integer array in C++

I have another task for my school and it is:

Write a program which will output the largest from three inputed numbers

So far I have done this:

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    int* numbers = new int[3];

    for(int i = 0; i < 3; i++) {
        cout << "Input number no. " << (i + 1);
        cin >> numbers[i];
        cout << endl;
    }


    system("PAUSE");
    return EXIT_SUCCESS;
}

Is there a helper function/method in C++ which will find a largest number in my numbers array?

Upvotes: 1

Views: 4846

Answers (3)

Pete Becker
Pete Becker

Reputation: 76245

You don't need an array here. Just look at the numbers as they come in:

int largest = std::numeric_limits<int>::min();
for (int i = 0; i < 3; ++i) {
    int value;
    std::cin >> value;
    if (largest < value)
        largest = value;
}

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 476970

There's an algorithm that finds the maximal element in a container (std::max_element), but that's inappropriate. Your situation can be solved with constant memory consumption, so you don't need to store all numbers. At any given point, you just need to remember the current maximum.

Imagine you had to process one gazillion numbers. Then storing them all would not be desirable.

Of course, internally the max_element algorithm does the same as I just suggested, but it assumes that you already have the container anyway. If you don't, then just update the maximum on the fly. The boost.accumulators library has something to do that, but I'm sure you can write this yourself — it should only take one or two lines.

Upvotes: 3

GraphicsMuncher
GraphicsMuncher

Reputation: 4641

In the following code snippet, max will contain the highest number from the list:

int i;
int max=numbers[0];
for(i=1;i<3;i++)
{
   if(numbers[i]>max) max=numbers[i];
}

Note: Your array looks too small - it has a size of two and I'm pretty sure you want a size of three.

Upvotes: 3

Related Questions