Largest Element in Array

Arrays

Grab The Best Job for you

example, category, and, terms

Share now

Definition & Explanation

This program takes an array of numbers as input and finds the largest element in the array. It initializes a variable max with the first element of the array and then iterates through the remaining elements of the array. During each iteration, it compares the current element with the max variable. If the current element is greater than max, it updates the value of max to the current element. After iterating through all elements, the program returns the value of max, which represents the largest element in the array.

Program Logic

  1. Start
  2. Declare an array arr of integers.
  3. Initialize a variable max with the first element of the array (arr[0]).
  4. Iterate through the array from index 1 to n-1 (where n is the length of the array).
    • If arr[i] is greater than max, update max with the value of arr[i].
  5. After iterating through all elements, max will contain the largest element in the array.
  6. Return max.
  7. End.
C

Method 1 :

#include <stdio.h>

int findLargestElement(int arr[], int n) {
    int max = arr[0];
    for (int i = 1; i < n; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }
    return max;
}

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int n = sizeof(arr) / sizeof(arr[0]);
    int largest = findLargestElement(arr, n);
    printf("The largest element in the array is: %d\n", largest);
    return 0;
}

Output :

C++

Method 1 :

#include <iostream>
using namespace std;

int findLargestElement(int arr[], int n) {
    int max = arr[0];
    for (int i = 1; i < n; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }
    return max;
}

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int n = sizeof(arr) / sizeof(arr[0]);
    int largest = findLargestElement(arr, n);
    cout << "The largest element in the array is: " << largest << endl;
    return 0;
}

Output :

JAVA

Method 1 :

public class Main {
    public static int findLargestElement(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, 20, 30, 40, 50};
        int largest = findLargestElement(arr);
        System.out.println("The largest element in the array is: " + largest);
    }
}

Output :

Python

Method 1 :

a=[10,89,9,56,4,80,8]
max_element=a[0]

for i in range(len(a)):
    if a[i]> max_element:
        max_element=a[i]


print(max_element)

Output :

89

Leave a Reply

Your email address will not be published. Required fields are marked *