How to Find the Smallest Number in an Array in C++?
Last Updated :
13 Feb, 2024
In C++, arrays are the data types that store the collection of the elements of other data types such as int, float, etc. In this article, we will learn how to find the smallest number in an array using C++.
For Example,
Input:
myVector = {10, 3, 10, 7, 1, 5, 4}
Output:
Smallest Number = 1
Find the Smallest Number in an Array in C++
To find the smallest number in an array in C++, we can use the std::min_element() function that works on the range of data given to it as an argument.
The syntax of std::min_element() is:
min_element(start, end);
Here, the start and end are the the pointers or iterators to the beginning and the end of the range respectively.
This function returns the pointer or iterator to the minimum element in the range.
C++ Program to Find the Smallest Number in an Array in C++
C++
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
int arr[] = { 1, 45, 54, 71, 76, 12 };
int n = sizeof (arr) / sizeof (arr[0]);
int min_num = *min_element(arr, arr + n);
cout << "Smallest number in the array is: " << min_num
<< endl;
return 0;
}
|
Output
The smallest number in the array is: 3
Time complexity: O(n)
Space complexity: O(1)
Share your thoughts in the comments
Please Login to comment...