Smallest Element in an array using C++

Find smallest element in an array using C++

In this program we will find the smallest element in the given unsorted array. We will initialize the starting element of array as smallest one and compare with all other elements of the given array and upadte the smallest value.

Sample Test Case

Enter the size of array : 6
Enter the elements of array : 2 0 8 44 6 17
Output
Smallest element of array : 0

Finding Smallest Element in an Array using C++

Algorithm

  1. Start.
  2. Declare an array of given size.
  3. Initialize smallest to arr[0].
  4. Traverse the entire array using for loop.
  5. If arr[n] < smallest, update smallest to arr[n].
  6. Once we reach the end of loop, display the current value of smallest.
  7. End.

C++ Code

#include <bits/stdc++.h>
using namespace std;

int main()
{
    int size;
    
    cout << “Enter size of array : “ << endl;
    
    cin >> size;
    int arr[size];
    
    cout << “Enter elements of array : “ << endl;
    
    for(int i=0i<sizei++)
    {
        cin >> arr[i];
    }
    
    int smallest = arr[0];   // initialize smallest to arr[0]
    
    for(int i=1i<sizei++)  
    {
        if(arr[i]<smallest)   // compare current element with smallest
        {
            smallest = arr[i];
        }
    }
    
    cout << “Smallest Element in the array : “ << endl << smallest;  // display result

    return 0;
}


Output

Enter size of array :                                                                                                                          
6     

Enter elements of array :                                                                                                                      
2 0 8 44 6 7   
                                                                                                                                
Smallest Element in the array :                                                                                                                
0 
 

This page is contributed by Rishav Raj.