# Get the first three maximum numbers in an array in C+

In this tutorial, we will be learning about, how to get the first three maximum numbers in an array in C++.

## How to get the first three maximum numbers in an array using C++

Here, we will discuss various methods by which we can get the first three maximum numbers in an array with C++.

### METHOD 1

Example program…

#include <iostream> #include<bits/stdc++.h> using namespace std; int main() { int n; cout<<"Enter the size of array\n"; cin>>n; int arr[n]; cout<<"Enter the elements of the array\n"; for(int i=0;i<n;i++) { cin>>arr[i]; } int first,second,third; first=second=third=arr[0]; for(int i=0;i<n;i++) { if(arr[i]>first) { third=second; second=first; first=arr[i]; } else if(arr[i]>second) { third=second; second=arr[i]; } else if(arr[i]>third) third=arr[i]; } cout<<"The first three maximum numbers are : "<<first<<" "<<second<<" "<<third; return 0; }

Output :

Enter the size of array 8 Enter the elements of the array 23 5 78 34 78 34 23 90 The first three maximum numbers are : 90 78 78

Explanation :

1. First we need to take the size of the array and also the array elements from the user.

2. Then, we declare three variables named first, second, and third and initialized them to the first element of the array.

3. Now, we run a loop and check the conditions and change the first, second, and third variables.

4. Then, we just print the first, second, and third greater elements.

### METHOD 2

Example Program…

#include <iostream> #include<bits/stdc++.h> using namespace std; int main() { int n; cout<<"Enter the size of array\n"; cin>>n; int arr[n]; cout<<"Enter the elements of the array\n"; for(int i=0;i<n;i++) { cin>>arr[i]; } for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { if(arr[i]<arr[j]) { int temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } } } cout<<"The first three maximum numbers are : "<<arr[0]<<" "<<arr[1]<<" "<<arr[2]; return 0; }

Output :

Enter the size of array 5 Enter the elements of the array 1 5 6 7 8 The first three maximum numbers are : 8 7 6

Explanation :

1. First we need to take the size of the array and also the array elements from the user.

2. Then, we need to sort an array in descending order by using a temporary variable.

3. Then, we just print the first, second, and third elements of the array. i.e… arr[0], arr[1], and arr[2].

## Leave a Reply