-4

I have a question it seems easy but i can not solve it Array of n integers is given. Find the two biggest elements in array. I found the first one can not find second one. Please help me to find the second one.

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin >> n;
    int a[n];
    for(int i=0;i<n;i++) {
        cin>>a[i];
    }

    int maks=a[0];
    for (int i=1;i<n;i++) {
        if(a[i]>maks) {
            maks=a[i];
        }
    }
    cout << maks;
}
WhozCraig
  • 59,130
  • 9
  • 69
  • 128

1 Answers1

1

Here is the snippet to find second biggest element in a array,

#include <iostream>
using namespace std;
int main() {
    int n;
    cin >> n;
    int *a = new int[n];

    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    int top2element[2];
    if (a[0] > a[1]) {
        top2element[0] = a[0];
        top2element[1] = a[1];
    }
    else {
        top2element[1] = a[0];
        top2element[0] = a[1];
    }

    for (int i = 2; i < n; i++) {
        if (a[i] > top2element[0])
        {

            top2element[1] = top2element[0];
            top2element[0] = a[i];
        }
        else if (a[i] > top2element[1]) {
            top2element[1]= a[i];
        }
    }
    cout << top2element[0]<<endl;//biggest
    cout << top2element[1];//second biggest

    delete a;
}

Note: allocate memory dynamically if input stream is of unknown size

TruthSeeker
  • 1,124
  • 8
  • 17