-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLargestInArray.cpp
46 lines (46 loc) · 1.08 KB
/
LargestInArray.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
#include<iostream>
using namespace std;
int main()
{
int a[50],n,max1,max2,pos1,pos2;
cout<<"Enter the no. of elements of the array: "<<endl;
cin>>n;
cout<<"Enter the elements of the array: "<<endl;
for(int i=0; i<n; i++)
{
cin>>a[i];
}
//To check the 1st Largest number of the array
max1=a[0];
for(int i=0; i<n; i++)
{
if(max1<=a[i])
{
max1=a[i];
pos1=i;
}
}
cout<<"Largest Element of the array is "<<max1<<" at position "<<++pos1<<endl;
//To find the 2nd Largest number of the array
for(int i=0; i<n; i++)
{
if(a[i]==max1)
continue;
else
{
max2=a[i]; //To set the value of max2 other than max
break;
}
}
//This loop finds 2nd Largest number
for(int i=0; i<n; i++)
{
if(a[i]>max2 && a[i]!=max1)
{
max2=a[i];
pos2=i;
}
}
cout<<"Second Largest Element of the array is "<<max2<<" at position "<<++pos2<<endl;
return 0;
}