Finding the largest element in an array is a common programming task. This involves iterating through the array elements and keeping track of the maximum value encountered so far. Whether you're using C, C++, Python, or Java, the basic approach remains similar - initialize a variable with the first element of the array, then loop through the remaining elements, updating the maximum value as needed. Once the loop is completed, you'll have the largest element of the array. Below are examples of how to accomplish this in various programming languages.
#include <stdio.h>
int findLargest(int arr[], int size) {
int max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
int main() {
int arr[] = {10, 15, 7, 20, 5};
int size = sizeof(arr) / sizeof(arr[0]);
int largest = findLargest(arr, size);
printf("The largest element is: %d
", largest);
return 0;
}
#include <iostream>
using namespace std;
int findLargest(int arr[], int size) {
int max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
int main() {
int arr[] = {10, 15, 7, 20, 5};
int size = sizeof(arr) / sizeof(arr[0]);
int largest = findLargest(arr, size);
cout << "The largest element is: " << largest << endl;
return 0;
}
def find_largest(arr):
return max(arr)
arr = [10, 15, 7, 20, 5]
largest = find_largest(arr)
print("The largest element is:", largest)
public class LargestElement {
public static int findLargest(int[] arr) {
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
public static void main(String[] args) {
int[] arr = {10, 15, 7, 20, 5};
int largest = findLargest(arr);
System.out.println("The largest element is: " + largest);
}
}