C PROGRAM FOR Mth LARGEST AND Mth SMALLEST ELEMENT IN AN ARRAY
Consider the following I/O samples.
SAMPLE INPUT: 6
2 4 5 1 6 3
2
SAMPLE OUTPUT: 5 //2nd largest element
2 //2nd smallest element
The algorithm used here is :
- Input the number of elements.
- Input the array elements.
- Input the Mth value.
- Sort the array.
- Print the output for Mth largest and Mth Smallest.
C PROGRAM:
#include<stdio.h>
int main()
{
int n,a[100],i,j,m,temp;
printf("Enter the number of elements:");
scanf("%d",&n);
printf("Enter the array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the Mth Value:");
scanf("%d",&m);
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i] > a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("\nMth Largest Element is : %d\n",a[n-m]);
printf("Mth Smallest Element is : %d",a[m-1]);
return 0;
}
OUTPUT:
The given source code in C program "to find the Mth largest and smallest element in an array" is short and simple to understand. The source code is well tested in DEV-C++ and is completely error free.
If you have any feedback about this article and want to improve this, please comment in the comment section.
Comments
Post a Comment