Google News
logo
C++ Program to Find Largest Element in an Array
In the following example of C++ program to find the largest element in an array :
Program :
#include <iostream>
#include <limits>

int main() {
    const int SIZE = 5;
    int arr[SIZE];
    std::cout << "Enter " << SIZE << " integers: ";
    for (int i = 0; i < SIZE; i++) {
        std::cin >> arr[i];
    }
    int largest = arr[0];
    for (int i = 1; i < SIZE; i++) {
        if (arr[i] > largest) {
            largest = arr[i];
        }
    }
    std::cout << "The largest element in the array is " << largest << std::endl;
    return 0;
}
Output :
Enter 5 integers: 7
12
5
19
8
The largest element in the array is 19
* This program creates an array arr of size SIZE (which is set to 5 in this example), and prompts the user to enter SIZE integers. It then uses a for loop to iterate over each element of the array, and stores the input in the corresponding element.

* The program then initializes a variable largest to the first element of the array arr[0]. It then uses another for loop to iterate over each element of the array starting from the second element arr[1].

* For each element arr[i], the program checks whether it is greater than largest. If it is, the program updates largest to the new value of arr[i].

* After the loop completes, largest will contain the largest element in the array. Finally, the program outputs the largest element to the console using std::cout.