In this tutorial, we will learn and write a print the largest element in an array in C++. To understand the coding, you should have knowledge of the following topics in C++ programming:
1. C++ program to find the largest element in an array
The program takes user input for the size and the values of elements of an array. Lastly, displays the largest element present in the array.
The first element in an array is assumed to be the largest element then iterating the array using for loop, we compare each of the elements present in an array. Whenever the element is found to be smaller then the value is inserted into the largest variable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #include<iostream> using namespace std; int main() { int arr[50], size, largest, i; cout<<"Enter the size of an array: "; cin>>size; cout<<"Enter " << size << " Array Elements:\n"; for(i = 0; i < size; i++) cin>>arr[i]; //assuming first element to be largest largest = arr[0]; for(i = 1; i < size; i++) { if(largest<arr[i]) largest = arr[i]; } //Display the result cout << "\nLargest Element in an array: " << largest; return 0; } |
Output:
Enter the size of an array: 5
Enter 5 Array Elements:
25
12
58
5
12
Largest Element in an array: 58
2. Using Function
The program logic is the same as the above only difference is we will create a separate function to search for the largest element and return the value from that function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | #include<iostream> using namespace std; //function to find largest element int findLargest(int a[], int s) { int i, large; large = a[0]; for(i=1; i<s; i++) { if(large < a[i]) large = a[i]; } return large; } //main function int main() { int arr[100], size, largest, i; cout<<"Enter the size of an array: "; cin>>size; cout<<"Enter " << size << " Array Elements:\n"; for(i=0; i<size; i++) cin>>arr[i]; largest = findLargest(arr, size); cout<<"\nLargest Element in an array: "<<largest; return 0; } |
Output:
Enter the size of an array: 5
Enter 5 Array Elements:
53
2
70
23
11
Largest Element in an array: 70