1

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?

asked Nov 5, 2012 at 0:39
3
  • 1
    Yes, there is std::max_element: en.cppreference.com/w/cpp/algorithm/max_element It requires iterators as arguments (one to the beginning, one to the end of the array). You can use pointers as iterators. Commented Nov 5, 2012 at 0:41
  • 1
    Your input code is wrong. If you don't understand why, make sure you learn how to use iostreams in C++. As a test, your program must survive if you call echo "" | myprogram. Commented Nov 5, 2012 at 0:46
  • Since you know that there will be three numbers, you can just use int numbers[3] instead of creating the array with new and forgetting to delete it. Commented Nov 5, 2012 at 13:26

3 Answers 3

3

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.

answered Nov 5, 2012 at 0:46
3

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.

answered Nov 5, 2012 at 0:42
0
0

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;
}
answered Nov 5, 2012 at 13:25

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.