
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Largest Element of an Array in C++
An array contains multiple elements and the largest element in an array is the one that is greater than other elements.
For example.
5 | 1 | 7 | 2 | 4 |
In the above array, 7 is the largest element and it is at index 2.
A program to find the largest element of an array is given as follows.
Example
#include <iostream> using namespace std; int main() { int a[] = {4, 9, 1, 3, 8}; int largest, i, pos; largest = a[0]; for(i=1; i<5; i++) { if(a[i]>largest) { largest = a[i]; pos = i; } } cout<<"The largest element in the array is "<<largest<<" and it is at index "<<pos; return 0; }
Output
The largest element in the array is 9 and it is at index 1
In the above program, a[] is the array that contains 5 elements. The variable largest will store the largest element of the array.
Initially largest stores the first element of the array. Then a for loop is started which runs from the index 1 to n. For each iteration of the loop, the value of largest is compared with a[i]. If a[i] is greater than largest, then that value is stored in largest. And the corresponding value of i is stored in pos.
This is demonstrated by the following code snippet.
for(i=1; i<5; i++) { if(a[i]>largest) { largest = a[i]; pos = i; } }
After this, the value of the largest element in the array and its position is printed.
This is shown as follows −
cout<<"The largest element in the array is "<<largest<<" and it is at index "<<pos;