Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

1. Mathematical Operations on an Array.

a) Write a C program to find the second largest and smallest elements in a given array.
by

1 Answer

aashaykumar

#include <stdio.h>

int secondSmallest(int arr[],int n)
{
int min = arr[0];
int second_min = arr[0] ;
int i;
for(i = 0; i < n; i++) //Array Traversal
{
if(arr[i] < min)
{
second_min = min;
min = arr[i];
}
else if(arr[i] < second_min && arr[i] != min) //Check for second smallest
{
second_min = arr[i];
}
}
return second_min; //Return second smallest
}
int secondLargest(int arr[],int n)
{
int i, first, second;
if (n < 2) {
printf(" Invalid Input ");
return;
}
first = second =arr[0]; //Array Traversal
for (i = 0; i < n; i++)
{
if (arr[i] > first)
{
second = first;
first = arr[i];
}

else if (arr[i] > second && arr[i] != first) //Check for second largest
{
second = arr[i];
}
}
return second; //Return second largest
}
int main() {
int n;
printf("Enter the number of elements:");
scanf("%d",&n);
printf("Enter the array elements :");
int a[n]; //Array Declaration
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
if(n<2)
{
printf("Invalid Input");
}
else
{
int sS=secondSmallest(a,n);
printf("The second smallest element is %d",sS);
printf("\n");
int sL=secondLargest(a,n);
printf("The second largest element is %d",sL);
}
return 0;
}

Login / Signup to Answer the Question.