-
Notifications
You must be signed in to change notification settings - Fork 16
/
SecondLargestElementInArray.cpp
51 lines (43 loc) · 1.04 KB
/
SecondLargestElementInArray.cpp
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
43
44
45
46
47
48
49
50
51
#include<iostream>
using namespace std;
void second_largest(int nums[], int arr_size)
{
int i, first_element, second_element;
/* There should be atleast two elements */
if (arr_size < 2)
{
cout<< " Invalid Input ";
return;
}
first_element = second_element = INT_MIN;
for (i = 0; i < arr_size ; i ++)
{
if (nums[i] > first_element)
{
second_element = first_element;
first_element = nums[i];
}
else if (nums[i] > second_element && nums[i] != first_element)
{
second_element = nums[i];
}
}
if (second_element == INT_MIN)
{
cout<< "No second largest element";
}
else
{
cout<< "\nThe second largest element is: " <<second_element;
}
}
int main()
{
int nums[] = {7, 12, 9, 15, 19, 32, 56, 70};
int n = sizeof(nums)/sizeof(nums[0]);
cout << "Original array: ";
for (int i=0; i < n; i++)
cout << nums[i] <<" ";
second_largest(nums, n);
return 0;
}