How to Find Minimum Value in C++ Array

C-Plus-Plus-array

In this tutorial, we are going to learn about different methods of how to Find Minimum Value in C++ Array. We will learn this by using multiple techniques by using basic to advanced C++.So let us begin.

1.Find Minimum Value in C++ Array entered by user


In this example program, we are first taking n number of input elements from the user. Then we are finding the smallest number from this input array. When we have the result then finally display it.

Program to Find Minimum Value in C++ Array

#include <iostream>
using namespace std;

int main()
{
    int Arraylen;
    float Testarr[100];

    cout << "Enter the Desired length of array between 1 to 100: ";
    cin >> Arraylen;
    cout << endl;

    for(int k = 0; k < Arraylen; ++k)
    {
       cout << "Enter the elements at index : " << k  << " : ";
        cin >> Testarr[k];
    }

    for(int i = 1;i < Arraylen; ++i)
{
       if(Testarr[0] > Testarr[i])
           Testarr[0] = Testarr[i];
    }
    cout << "The Smallest Number in input Array is = " << Testarr[0];

    return 0;
}

Output

Enter the Desired lenght of array between 1 to 100: 5

Enter the elements at index : 0 : 9
Enter the elements at index : 1 : 8
Enter the elements at index : 2 : 6
Enter the elements at index : 3 : 5
Enter the elements at index : 4 : 2
The Smallest Number in input Array is = 2

2. STL libaray to Find Minimum Value in C++ Array


In this example, we are going to learn about the STL algorithm min_element() method to find the Smallest element or minimum value in an array.

Program to Find Minimum Value in C++ Array

#include <iostream>
#include <algorithm>
using namespace std;
 
int main()
{
    int Testarr[] = { 45, 32, 21, 61, -14, 3 };
 
    int *smallest = std::min_element(std::begin(Testarr), std::end(Testarr));
 
    std::cout << "The Smallest element in the Array is " << *smallest << std::endl;
 
    return 0;
}

Output

The Smallest element in the Array is -14

Summary

In this post, we have learned how to Find Minimum Value in C++ Array.