-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path4_second_largest.cpp
More file actions
42 lines (37 loc) · 854 Bytes
/
Copy path4_second_largest.cpp
File metadata and controls
42 lines (37 loc) · 854 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <climits>
#include <vector>
using namespace std;
void second_largest(int target[], int n)
{
if (n < 2)
{
cout << "Array must have at least two elements." << endl;
return;
}
int first = 0;
int second = 0;
for (int i = 0; i < n; i++)
{
if (target[i] > first)
{
second = first;
first = target[i];
}
else if (target[i] > second && target[i] != first)
{
second = target[i];
}
}
if (second == 0)
cout << "No second largest element found." << endl;
else
cout << "The second largest element is " << second << endl;
}
int main()
{
int target[] = {3, 6, 7, 12, 56, 789, 34};
int n = sizeof(target) / sizeof(target[0]);
second_largest(target, n);
return 0;
}