In this post, you will learn how to Find Largest Element in an Array using C++ programming language.
This lesson will teach you how to Find Largest Element in an Array, using assignment operators, decision making statement and the for loop statement using the C++ Language. Let’s look at the below source code.
How to Find Largest Element in an Array?
RUN CODE SNIPPETSource Code
#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
The statements #include<iostream>, using namespace std, int main are the main factors that support the function of the source code.
Now we can look into the working and layout of the code’s function.
- Initialize the variable a as an array “[ ]” which holds the integer values and assign the values to a.
- Initialize the string values largest, i, pos as integers and assign the variable
largest = a[0]
- Declare the for loop with the condition
(i=1; i<5; i++)
and in the body of the loop declare an if statement with the condition(a[i]>largest)
. - In the loop statement using the assignment operator perform the following operations.
{ largest = a[i]; pos = i; } - Using the output function cout display the output statements with the integer which holds the answer, and end the source with a return function.