Find the largest three elements in an array using C++
In the following tutorial, we are going to learn how to find the three largest elements in an array in C++. So, let’s start with the code:
#include<iostream> using namespace std; int main() { int ar[]={1021,200,6549,100,3456,901,1111,800,9999,999}; int max=0,l,h=3; cout<<"The three largest elements in the given array is:"<<endl; P: for(int j=0;j<10;j++) { if(ar[j]>max) { max=ar[j]; l=j; } } ar[l]=0; cout<<max<<" "; max=0; h=h-1; if(h>0) { goto P; } return 0; }
Three largest array elements in the given array – Explanation
In the above code, we have used an array ar which contains 10 elements. From this given array we have to find the three largest elements. So, here we need three variables max for storing the largest element, l for storing the position of the largest element and h for keeping the count of 3 as we have to find 3 largest elements.
Set max=0 and h=3.
Here, we use a for loop to find the largest element in a given array ar. Once we found the largest element we store it in variable max and its position in variable l. Now, we print that element then we reinitialize the max to 0 and we also remove that element from the array ar using variable l by reinitializing ar[l]=0.
Then we decrement h by 1 because we have found 1st largest element. Now, we check whether h>0 or not, if yes then we use goto statement and send the control to the for loop used above to find the next largest element. We repeat these steps until we found all the three largest elements.
Output:
The three largest elements in the given array is: 9999 6549 3456
That’s all. Thank You.
Leave a Reply