Program to find largest element in an array
Given an array, find the largest element in it.
Example:
Input : arr[] = {10, 20, 4} Output : 20 Input : arr[] = {20, 10, 20, 4, 100} Output : 100
The solution is to initialize max as first element, then traverse the given array from second element till end. For every traversed element, compare it with max, if it is greater than max, then update max.
// C++ program to find maximum // in arr[] of size n #include <bits/stdc++.h> using namespace std; int largest( int arr[], int n) { int i; // Initialize maximum element int max = arr[0]; // Traverse array elements // from second and compare // every element with current max for (i = 1; i < n; i++) if (arr[i] > max) max = arr[i]; return max; } // Driver Code int main() { int arr[] = {10, 324, 45, 90, 9808}; int n = sizeof (arr) / sizeof (arr[0]); cout << "Largest in given array is " << largest(arr, n); return 0; } // This Code is contributed // by Shivi_Aggarwal |
Output:
Largest in given array is 9808
Using Library Function :
We use std::max_element in C++.
// C++ program to find maximum in arr[] of size n #include <bits/stdc++.h> using namespace std; // returns maximum in arr[] of size n int largest( int arr[], int n) { return *max_element(arr, arr+n); } int main() { int arr[] = {10, 324, 45, 90, 9808}; int n = sizeof (arr)/ sizeof (arr[0]); cout << largest(arr, n); return 0; } |
Output :
9808
Time complexity of the above solution is .
Last Updated on October 16, 2021 by admin