How to find the smallest element in an array in C++

C++ is a language that covers all the essential aspects of programming. However, no built-in function can give us the smallest number in an array. For that, we would need to make a function of it from scratch. In this Answer, we will discuss the C++ code to have the smallest number in an array.

Smallest element in an array
Smallest element in an array

Explanation

Let us consider a scenario in which we are given an array and want to find the smallest element. We will make a variable that keeps small the smallest element up to which the array has traversed. We will initialize small with the maximum value of an integer (2147483647).

Then we will start traversing the array. As we capture the element in an array that is less than the value of the variable small, we will update small. In this way, we keep traversing and updating small as shown in the diagram below.

svg viewer
Dry run example illustrating how the algorithm works
Dry run example illustrating how the algorithm works

Code

#include <iostream>
using namespace std;
#include <climits>
int smallestElement(int arr[],int size)
{
int small=INT_MAX;
for(int ri=0;ri<size;ri++)
{
if(small>arr[ri])
{
small=arr[ri];
}
}
return small;
}
int main()
{
int size=5;
int arr[size]={23,4,-1,90,-9};
int small=smallestElement(arr,size);
cout<<"\nThe smallest element of an array : "<<small;
}

  • Line 4–16: Find the smallest element by comparing the current value of the small variable with each element of the array. It will only update small , if the condition at line 10 holds.

  • Line 19–20: Initialize an array of size 5.

  • Line 21: Call a smallestElement() function.

Conclusion

This Answer explains the process to find the minimum number from the array and looked at the dry-run illustration of the code. Implementing these functions from scratch is beneficial for beginners in programming as it requires a proper understanding of the array and how we can traverse it. This function provides meaningful information about the data.

Note: Similarly, the largest element element in the array can also be found.

Q

What is the role of the small variable in the code?

A)

It holds the sum of all elements in the array.

B)

It stores the index of the largest element in the array.

C)

It stores the average of all elements in the array.

D)

It keeps track of the smallest element found so far.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved