C++ Programming

Write a program to calculate the highest two numbers in an array with length n, and print these numbers with their indexes.

Method 1

#include <iostream>
using namespace std;
 
int main ()
{
//Function to implement bubble sort
void bubbleSorting(int arr[], int num);
int x, num;

cout << "Enter the number of elements " << "\n"; 
cin >> num;
  
int *arr = new int (num);	
cout << "Enter " << num << " numbers" << endl;

for(x=0;x< num; x++)
{
  cin >> arr[x];		
}
bubbleSorting(arr, num); 
}

void bubbleSorting(int arr[], int num)  
{
    int i, j;
    
    for (i = 0; i < num - 1; i++)
     for (j = 0; j < num - i - 1; j++){
      if (arr[j] > arr[j + 1]) 
       swap(arr[j], arr[j + 1]);
}
        
    cout << "Largest number is : " << arr[num -1] << " at index: " << num -1 << endl;
    cout << "Second Largest number is : " << arr[num -2] << " at index: " << num -2 << endl;
        
    return;
}

Output

Enter the number of elements 
6
Enter 6 numbers
23
32
45
12
8
37
Largest number is : 45 at index: 5
Second Largest number is : 37 at index: 4

Method 2

#include <iostream>
#include <climits> // For INT_MIN
using namespace std;


void findTwoHighest(int arr[], int n) {
    
    int Highest = INT_MIN, secondHighest = INT_MIN;
    int HighestIndex = -1, secondHighestIndex = -1;

for (int i = 0; i < n; i++) {
        if (arr[i] > Highest) {
            secondHighest = Highest;
            secondHighestIndex = HighestIndex;
            Highest = arr[i];
            HighestIndex = i;
        } else if (arr[i] > secondHighest && arr[i] != Highest) {
            secondHighest = arr[i];
            secondHighestIndex = i;
        }
    }

if (secondHighest == INT_MIN) {
        cout << "There is no second highest number.\n";
    } else {
        cout << "Highest number: " << Highest << " at index " << HighestIndex << endl;
        cout << "Second Highest number: " << secondHighest << " at index " << secondHighestIndex << endl;
    }
}

int main() {
    int n;
    cout << "Enter the number of elements: ";
    cin >> n;

int arr[n];
    cout << "Enter the numbers:\n";
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
}

findTwoHighest(arr, n);
return 0;

}

Output

Enter the number of elements: 6
Enter the numbers:
23
105
25
12
36
58
Highest number: 105 at index 1
Second Highest number: 58 at index 5
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments