How to find the largest element in an array in C++
Sometimes we need to find the largest element in an array for several reasons. However, C++ has no built-in function that takes an array as an input and returns the largest element. So we need to design our own function.
There are several methods to solve this problem. In this Answer, we will discuss only two methods explained below.
Method 1
In this method, we will make a function that returns the largest elements in an array.
Parameters of the function
As shown below in the code, the parameters of the function,largestElement(), are arr and size (size of the array).
Return value
It returns the large variable which contains the largest element of the array.
Now you have a basic understanding of the working of the function. First, we will look at the code, and then we will explain the core mechanism of the code.
Code
#include <iostream>using namespace std;#include <climits>int largestElement(int arr[],int size){int large=arr[0];for(int ri=0;ri<size;ri++){if(large<arr[ri]){large=arr[ri];}}return large;}int main(){int size=5;int arr[size]={2,7,23,90,7};int large=largestElement(arr,size);cout<<"\nThe largest element of an array : "<<large;}
Code explanation
The explanation of the code is given below.
Line 4–16: Finds the largest element by comparing the current value of
largevariable with each element of the array. It will only update thelarge, if the condition of line 10 holds. This condition ensures thatlargehas the largest element up to the indices we traversed in an array.Line 19–20: Initializes an array of size 5.
Line 21: Calls the
largestElement()function.
Complexity analysis
The time and space complexity of finding the largest element from the array through this method is
Method 2
In this method, first, we sort an array, and when sorted in descending order, we return the value present in the first index of the array.
Code
#include <iostream>#include <algorithm>using namespace std;int main(){int arr[] = {5, 2, 9, 1, 5, 6};int size = sizeof(arr) / sizeof(arr[0]);sort(arr, arr + size, greater<int>());cout<<"\nThe largest element of an array : "<<arr[0];return 0;}
Code explanation
The explanation of the code is given below.
Line 7: Initializes an array with six elements.
Line 8: Computes the size of an array. It will be helpful when calling the
sort()function.Line 9: Sorts an array from the starting index to the ending.
greater<int>()defines the need to sort an array in descending order.Line 10: Prints the first element of the array because after the sorting operation, the largest element is at the array's first index.
Complexity analysis
The time complexity of finding the largest element after sorting an array is
Note: To learn about the smallest element in the array, click on link.
What is the initial value of the variable largest?
0
The value of the first element in the array.
-1
The value of the last element in the array.
Free Resources