Given an array of integers, find the largest element in the array. You need to return the value of the largest element.
Input/Output Examples
Example 1:
- Input: arr = [10, 34, 56, 78, 99, 23, 67]
- Output: 99
Example 2:
- Input: arr = [-1, -22, -3, -45, -5]
- Output: -1
Approach to find the largest element in an array
- Initialize a variable to hold the maximum value (usually set to the first element of the array).
- Iterate through the array, comparing each element with the current maximum.
- Update the maximum value if a larger element is found during the iteration.
- After iterating through the entire array, the maximum value will hold the largest element in the array.
- Edge case: If the array is empty, handle it by returning an appropriate message or value depending on the requirements (in the provided codes, we assume the array is non-empty).
C++ Program to find the largest element in an array
cpp
#include <iostream>
#include <vector>
using namespace std;
// Function to find the largest element in the array
int findLargestElement(vector<int> arr) {
int maxElement = arr[0]; // Initialize the first element as the maximum
for (int i = 1; i < arr.size(); i++) {
if (arr[i] > maxElement) {
maxElement = arr[i]; // Update maxElement if a larger value is found
}
}
return maxElement;
}
int main() {
vector<int> arr = {10, 34, 56, 78, 99, 23, 67};
cout << "The largest element is: " << findLargestElement(arr) << endl;
return 0;
}
Java Program to find the largest element in an array
java
import java.util.Scanner;
public class LargestElement {
// Function to find the largest element in the array
public static int findLargestElement(int[] arr) {
int maxElement = arr[0]; // Initialize the first element as the maximum
for (int i = 1; i < arr.length; i++) {
if (arr[i] > maxElement) {
maxElement = arr[i]; // Update maxElement if a larger value is found
}
}
return maxElement;
}
public static void main(String[] args) {
int[] arr = {10, 34, 56, 78, 99, 23, 67};
System.out.println("The largest element is: " + findLargestElement(arr));
}
}
Python Program to find the largest element in an array
python
# Function to find the largest element in the array
def find_largest_element(arr):
max_element = arr[0] # Initialize the first element as the maximum
for i in range(1, len(arr)):
if arr[i] > max_element:
max_element = arr[i] # Update max_element if a larger value is found
return max_element
# Example usage
arr = [10, 34, 56, 78, 99, 23, 67]
print("The largest element is:", find_largest_element(arr))
Explanation of Code:
- Initialization: The variable
maxElement
(ormax_element
in Python) is initialized to the first element of the array. - Loop: The loop starts from the second element and compares it with
maxElement
. If a larger element is found,maxElement
is updated. - Return Value: After the loop completes, the
maxElement
contains the largest element, which is then returned.