JohnnyOnPc
JohnnyOnPc

Reputation: 444

Max In a C++ Array

I am trying to find the 'biggest' element in a user made array ,by using the max function from the algorithm library/header.

I have done some research on the cplusplus reference site but there I only saw how to compare two elements using the max function. Instead I am trying to display the maximum number using a function 'max' ,without having to make a 'for' loop to find it.

For example:

Array: array[]={0,1,2,3,5000,5,6,7,8,9} Highest value: 5000

I have made this code but it gives me a bunch of errors, which can be the issue?

#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
    int array[11];
    int n = 10;
    for (int i = 0; i < n; i++) {
       array[i] = i;
    }
    array[5] = 5000;
    max(array , array + n);
    for (int i = 0; i < n; i++)
        cout << array[i] << " ";
    return 0;
}

Upvotes: 23

Views: 135616

Answers (3)

vishal
vishal

Reputation: 2391

You can also use std::array by #include<array>

#include <iostream>
#include <algorithm>
#include <array>
using namespace std;
int main()
{
    array<int,10> arr;
    int n = 10;
    for (int i = 0; i < n; i++) {
        arr[i] = i;
    }
    arr[5] = 5000;
    
    cout<<"Max: "<< *max_element(arr.begin(),arr.end())<<endl;

    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    return 0;
}

More info on std::array

Upvotes: 3

Ardavel
Ardavel

Reputation: 1515

max_element is the function you need. It returns an iterator to the max element in given range. You can use it like this:

cout << " max element is: " << *max_element(array , array + n) << endl;

Here you can find more information about this function: http://en.cppreference.com/w/cpp/algorithm/max_element

Upvotes: 41

Marko Popovic
Marko Popovic

Reputation: 4153

Here is a modification of your program that does what you want:

#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
    int array[11];
    int n = 11;
    for (int i = 0; i < n; i++) {
        array[i] = i;
    }
    array[5] = 5000;

    cout << *std::max_element(array, array + n) << "\n";

    return 0;
}

Note that you had a bug in your program, you did not initialize the last element in your array. This would cause your array to contain junk value in the last element. I've fixed that by increasing n to 11. Note that this is OK because the condition in the for loop is i < n, which means that i can be at most 10, which is what you want.

Upvotes: 6

Related Questions