Find the Smallest and Largest Element in an Array
Understanding Smallest and Largest Element
Finding the smallest and largest element in an array involves scanning the array and keeping track of the minimum and maximum values encountered.
We will explore three different methods to find the smallest and largest element in an array using C++.
Method 1: Using Iteration
This method iterates through the array and finds the smallest and largest elements.
#include <iostream> #include <algorithm> using namespace std; void findSmallestLargest(int arr[], int n, int &smallest, int &largest) { smallest = largest = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] < smallest) smallest = arr[i]; if (arr[i] > largest) largest = arr[i]; } } int main() { int arr[] = {10, 20, 4, 45, 99, 23}; int smallest, largest; findSmallestLargest(arr, 6, smallest, largest); cout << "Smallest element: " << smallest << endl; cout << "Largest element: " << largest << endl; return 0; }
Largest element: 99
Method 2: Using Sorting
This method sorts the array and takes the first and last elements as the smallest and largest, respectively.
#include <iostream> #include <algorithm> using namespace std; int main() { int arr[] = {10, 20, 4, 45, 99, 23}; int n = 6; sort(arr, arr + n); cout << "Smallest element: " << arr[0] << endl; cout << "Largest element: " << arr[n - 1] << endl; return 0; }
Largest element: 99
Method 3: Using Recursion
This method finds the smallest and largest element using recursion.
#include <iostream> using namespace std; void findMinMax(int arr[], int n, int &min, int &max) { if (n == 1) { min = max = arr[0]; return; } int tempMin, tempMax; findMinMax(arr, n - 1, tempMin, tempMax); min = (arr[n - 1] < tempMin) ? arr[n - 1] : tempMin; max = (arr[n - 1] > tempMax) ? arr[n - 1] : tempMax; } int main() { int arr[] = {10, 20, 4, 45, 99, 23}; int smallest, largest; findMinMax(arr, 6, smallest, largest); cout << "Smallest element: " << smallest << endl; cout << "Largest element: " << largest << endl; return 0; }
Largest element: 99