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 :

    1. Input the number of elements.
    2. Input the array elements.
    3. Input the Mth value.
    4. Sort the array.
    5. 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

Popular posts from this blog

INVERTED PYRAMID STAR PATTERN

C PROGRAM TO PRINT ALL LEAP YEARS IN A GIVEN RANGE

Design a way to sort the list of positive integers in the descending order according to frequency of elements. The elements with integers with higher frequency come before with lower frequency elements with same frequency come in the same order as they appear the values.