Respuesta :
Answer:
Program for Second largest in an array:-
#include <bits/stdc++.h>
using namespace std;
int main()
{
int f,s,n; //declaring 3 variables f for first largest s for second largest n is size.
cin>>n;//taking input size of the array.
if(n<2)//n should be greater than 2..
cout<<"n should be greater than 2"<<endl;
int a[n];// array of size n.
for(int i=0;i<n;i++)
{
cin>>a[i];
}
f = s = INT_MIN;//initialising f and s with minimum value possible.
for (int i =0; i <n;i ++)
{
if (a[i] > f)
{
s = f;
f = a[i];
}
else if (a[i] > s && a[i] != f)
s = a[i];
}
if (s == INT_MIN)
cout<<"No second largest exists"<<endl;
else
cout<<"Second largest element is :"<<s;
return 0;
}
Program for second smallest element is:-
#include <bits/stdc++.h>
using namespace std;
int main()
{
int f,s,n; //declaring 3 variables f for first smallest s for second smallest n is size.
cin>>n;//taking input size of the array.
if(n<2)//n should be greater than 2..
cout<<"n should be greater than 2"<<endl;
int a[n];// array of size n.
for(int i=0;i<n;i++)
{
cin>>a[i];
}
f = s = INT_MAX;//initializing f and s with maximum value possible.
for (int i =0; i <n;i ++)
{
if (a[i]<f)
{
s = f;
f = a[i];
}
else if (a[i] < s && a[i] != f)
s = a[i];
}
if (s == INT_MAX)
cout<<"No second smallest exists"<<endl;
else
cout<<s;//it is the second smallest element...
return 0;
}
Explanation:
For Second largest:-
1. Declare 3 variables f, s and n. where n is size the array f is first largest and s is second largest.
2. Initialize f and s with minimum value possible.
3. Iterate over the array a and do the following steps:-
1.If element at ith position is greater than f. Then update f and s.
s=f and f=a[i].
2.If the element is between s and f then update s as.
s=a[i].
4. Print s because it is the second largest in the array.
For Second smallest:-
1. Declare 3 variables f, s and n. where n is size the array f is first smallest and s is second smallest.
2. Initialize f and s with minimum value possible.
3. Iterate over the array a and do the following steps:-
1.If element at ith position is smaller than f. Then update f and s.
s=f and f=a[i].
2.If the element is between s and f then update s as.
s=a[i].
4. Print s because it is the second smallest in the array.