max and min in array algorithm c++ code example

Example 1: find min and max in array c++

#include<iostream>

using namespace std;

public void getMax_MinValue(int arr[])
{
    int max, min;

    max = arr[0];
    min = arr[0];
    for (int i = 0; i < sizeof(arr); i++)
    {
        if (max < arr[i])
            max = arr[i];
        else if (min > arr[i])
            min = arr[i];
    }

    cout << "Largest element : " << max;
    cout << "Smallest element : " << min;
 
}

Example 2: max array c++

auto Max1 = *max_element(ForwardIt first, ForwardIt last);
auto Max2 = *max_element(ForwardIt first, ForwardIt last, Compare comp);

//Example:
#include <bits/stdc++.h>
using namespace std;
main() {
    vector<int> v{ 3, 1, -14, 1, 5, 9 }; 
    int result;
    
    result = *max_element(v.begin(), v.end());
    cout << "max element is: " << result << '\n'; // 9
 
    result = *max_element(v.begin(), v.end(), [](int a, int b) { return abs(a)<abs(b); });
    cout << "max element (absolute) is: " << result << '\n'; //-14
}

Tags:

Cpp Example