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