Program in C and C++ to find the second largest element in an array of n elements
C
CPP
#include<stdio.h> #define size 25 int Second_Max(int a[],int *n) { int l,sl,i; for(l=a[0],i=0;i<*n;i++) { if(a[i]>l) l=a[i]; } for(sl=0,i=0;i<*n;i++) { if(a[i]>sl&&a[i]!=l) sl=a[i]; } return sl; } int main(void) { int a[size],i,n; printf("Enter the size of array:-"); scanf("%d",&n); if(n>size) { printf("Invalid array size."); return 0; } printf("Enter %d numbers:-",n); for(i=0;i<n;i++) scanf("%d",&a[i]); int sl=Second_Max(a,&n); printf("Second largest element = %d",sl); return 0; }
#include<iostream> using namespace std; int Second_Max(int a[],int &n) { int l,sl,i; for(l=a[0],i=0;i<n;i++) { if(a[i]>l) l=a[i]; } for(sl=a[0],i=0;i<n;i++) { if(a[i]>sl&&a[i]!=l) sl=a[i]; } return sl; } int main(void) { const int size=25; int a[size],i,n; cout<<"Enter the size of array:-"; cin>>n; if(n>size) { cout<<"Invalid array size."; return 0; } cout<<"Enter "<<n<<" numbers:-"; for(i=0;i<n;i++) cin>>a[i]; int sl=Second_Max(a,n); cout<<"Second largest element = "<<sl; return 0; }
Output:-
Second method
0 Comments