Program in C and C++ to find the second largest element in an array of n elements
Second method
Second method
C
CPP
#include<stdio.h> #define size 25 int Second_Max(int a[],int *n) { int i,first,second; first=a[0]; second=a[1]; if(a[0]>a[1]) { first=a[0]; second=a[1]; } else { first=a[1]; second=a[0]; } for(i=2;i<*n;i++) { if(a[i]>first) { second=first; first=a[i]; } else if(a[i]>second) { second=a[i]; } } return second; } int main(void) { int a[size],i,n,sl; 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]); 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 i,first,second; first=a[0]; second=a[1]; if(a[0]>a[1]) { first=a[0]; second=a[1]; } else { first=a[1]; second=a[0]; } for(i=2;i<n;i++) { if(a[i]>first) { second=first; first=a[i]; } else if(a[i]>second) { second=a[i]; } } return second; } 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:-
Related Programs
0 Comments