c++ find min in array 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: min array c++

//Syntax
*min_element(ForwardIt first, ForwardIt last)
*min_element(ForwardIt first, ForwardIt last, Compare comp)
//Example:
#include <bits/stdc++.h>
using namespace std;

main() {
    vector<int> v{ 3, 1, -14, 6, 5, 9 }; 
    int result;
    
    result = *min_element(v.begin(), v.end());
    cout << "min element is: " << result << '\n'; //-14
 
    result = *min_element(v.begin(), v.end(), [](int a, int b) { return abs(a)<abs(b); });
    cout << "min element (absolute) is: " << result << '\n'; //1
}

Tags:

Cpp Example