Find Smallest Element in an Array

Understanding Finding Smallest Element

Finding the smallest element in an array involves scanning the array and keeping track of the minimum value encountered.

We will explore three different methods to find the smallest element in an array using C++.

Method 1: Using Iteration

This method iterates through the array and finds the smallest element.

#include <iostream>
#include <algorithm>
using namespace std;

int find_smallest(int arr[], int size) {
    int min_val = arr[0];
    for (int i = 1; i < size; i++) {
        if (arr[i] < min_val) {
            min_val = arr[i];
        }
    }
    return min_val;
}

int main() {
    int arr[] = {10, 20, 4, 45, 99, 23};
    int size = sizeof(arr) / sizeof(arr[0]);
    cout << "Smallest element: " << find_smallest(arr, size);
    return 0;
}
            
Output: Smallest element: 4

Method 2: Using Sorting

This method sorts the array and takes the first element as the smallest.

#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    int arr[] = {10, 20, 4, 45, 99, 23};
    int size = sizeof(arr) / sizeof(arr[0]);
    sort(arr, arr + size);
    cout << "Smallest element: " << arr[0];
    return 0;
}
            
Output: Smallest element: 4

Method 3: Using Recursion

This method finds the smallest element using recursion.

#include <iostream>
#include <algorithm>
using namespace std;

int find_smallest(int arr[], int n) {
    if (n == 1)
        return arr[0];
    int min_val = find_smallest(arr, n - 1);
    return (arr[n - 1] < min_val) ? arr[n - 1] : min_val;
}

int main() {
    int arr[] = {10, 20, 4, 45, 99, 23};
    int size = sizeof(arr) / sizeof(arr[0]);
    cout << "Smallest element: " << find_smallest(arr, size);
    return 0;
}
            
Output: Smallest element: 4
Top 100 Codes By Learn-for-free
Start Preparing Arraysform here👇

Below You will find some of the most important codes in languages like C, C++, Java, and Python. These codes are of prime importance for college semester exams and online tests.

Getting Started

Find Largest Element in an Array: C C++ Java Python

Find Smallest Element in an Array: C C++ Java Python

Find the Smallest and Largest Element in an Array: C C++ Java Python

Find Second Smallest Element in an Array: C C++ Java Python

Calculate the Sum of Elements in an Array: C C++ Java Python

Reverse an Array: C C++ Java Python

Sort First Half in Ascending Order and Second Half in Descending: C C++ Java Python

Finding the Frequency of Elements in an Array: C C++ Java Python

Counting the Number of Even and Odd Elements in an Array: C C++ Java Python

Finding Maximum Product Sub-array in a Given Array: C C++ Java Python

Finding Arrays are Disjoint or Not: C C++ Java Python

Finding Equilibrium Index of an Array: C C++ Java Python

Rotation of Elements of Array - Left and Right: C C++ Java Python

Balanced Parenthesis Problem: C C++ Java Python