File tree Expand file tree Collapse file tree 2 files changed +44
-0
lines changed Expand file tree Collapse file tree 2 files changed +44
-0
lines changed Original file line number Diff line number Diff line change @@ -98,5 +98,7 @@ This is a repository containing various C++ Programs to understand the basic con
98
98
99
99
C++ Code for finding the largest contiguous sum present in the given array.
100
100
101
+ * [ Second Largest Element in an Array] ( https://github.com/altruistcoder/Data-Structures/blob/master/second_largest_in_array.cpp ) :
101
102
103
+ C++ Code for finding the second largest element present in the given array.
102
104
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments