Program to find the 2nd largest number in an array
This is the program i written in my interview.There can be a better program or logic for the same
#include<stdio.h>
#include<conio.h>
int secondlargest(int s[],int k)
{
int s1[5],index,ind;
int max=s[0];
/* Find the max element in array and get its index*/
for(int i=1;i<k;i++)
{
if(s[i]>max)
{
max=s[i];
ind=i;
}
}
/*Substract the array elements from the maximum element and store the new elements in new array,make again the max element index position as max element to avoid having zero in array.*/
for(int i=0;i<k;i++)
{
s1[i]=max-s[i];
s1[ind]=max;
}
/*Now find the minimum element in the new array and get its index*/
int min=s1[0];
for(int i=1;i<k;i++)
{
if(s1[i]<min)
{
min=s1[i];
index=i;
}
}
/*Return the element having index of above step from the old array.You will have second max element of array*/
return s[index];
}
int main()
{
int arr[5]={35,81,49,1,90};
int s=secondlargest(arr,5);
printf("%d",s);
getch();
}
#include<stdio.h>
#include<conio.h>
int secondlargest(int s[],int k)
{
int s1[5],index,ind;
int max=s[0];
/* Find the max element in array and get its index*/
for(int i=1;i<k;i++)
{
if(s[i]>max)
{
max=s[i];
ind=i;
}
}
/*Substract the array elements from the maximum element and store the new elements in new array,make again the max element index position as max element to avoid having zero in array.*/
for(int i=0;i<k;i++)
{
s1[i]=max-s[i];
s1[ind]=max;
}
/*Now find the minimum element in the new array and get its index*/
int min=s1[0];
for(int i=1;i<k;i++)
{
if(s1[i]<min)
{
min=s1[i];
index=i;
}
}
/*Return the element having index of above step from the old array.You will have second max element of array*/
return s[index];
}
int main()
{
int arr[5]={35,81,49,1,90};
int s=secondlargest(arr,5);
printf("%d",s);
getch();
}
Comments
Post a Comment