Max In a C++ Array

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


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.


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

Tags:

C++

Arrays