Skip to content

Commit d25cabd

Browse files
committed
Second Largest Element in Array
1 parent 65232af commit d25cabd

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,5 +98,7 @@ This is a repository containing various C++ Programs to understand the basic con
9898

9999
C++ Code for finding the largest contiguous sum present in the given array.
100100

101+
* [Second Largest Element in an Array](https://github.com/altruistcoder/Data-Structures/blob/master/second_largest_in_array.cpp):
101102

103+
C++ Code for finding the second largest element present in the given array.
102104

second_largest_in_array.cpp

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#include <iostream>
2+
#include <limits.h>
3+
using namespace std;
4+
5+
void secondLargest(int a[], int n)
6+
{
7+
int i, first, second;
8+
if(n < 2)
9+
{
10+
cout<<"No. of elements in the array are less than two";
11+
return;
12+
}
13+
first = second = INT_MIN;
14+
for(i=0; i<n; i++)
15+
{
16+
// If current element is smaller than the 'first', then update both 'first' and 'second'
17+
if(a[i] > first)
18+
{
19+
second = first;
20+
first = a[i];
21+
}
22+
// If a[i] is in between 'first' and 'second' then update 'second'
23+
else if(a[i]>second && a[i]!=first)
24+
second = a[i];
25+
}
26+
if (second == INT_MIN)
27+
cout<<"There is no second largest element\n";
28+
else
29+
cout<<"The second largest element is "<<second;
30+
}
31+
32+
int main()
33+
{
34+
int a[100], n;
35+
cout<<"Enter total no. of elements in the array: ";
36+
cin>>n;
37+
cout<<"Enter the elements of the array: ";
38+
for(int i=0; i<n; i++)
39+
cin>>a[i];
40+
secondLargest(a, n);
41+
return 0;
42+
}

0 commit comments

Comments
 (0)