C program to find the second largest and smallest numbers in an array

C program to find the second largest and smallest numbers in an array

Enter the array items, and then use the swapping approach to arrange the numbers in descending order. Later, try printing the second-largest and second-smallest elements in an array using index location.

An array is used to store a collection of similar elements under a single identifier. The following are the array operations in the C programming language

  • Insert
  • Delete
  • Search

Program The C program to get the second largest and second smallest values in an array is provided below.

#include <stdio.h>

int main()
{
    int N;
    scanf("%d", &N);

    int counter, number[30];
    int temp;

    for (int i = 0; i < N; i++)
    {
        scanf("%d", &number[i]);
    }

    for (int i = 0; i < N; i++)
    {
        for (int j = i + 1; j < N; j++)
        {
            if (number[i] < number[j])
            {
                temp = number[i];
                number[i] = number[j];
                number[j] = temp;
            }
        }
    }

    printf("The numbers arranged in descending order ");

    for (int i = 0; i < N; i++)
    {
        printf("%d ", number[i]);
    }

    printf("\n");

    printf("The 2nd largest number is = %d \n", number[1]);
    printf("The 2nd smallest number is = %d \n", number[N - 2]);

    return 0;
}

Output When the above program is executed, it produces the following result −

5
Enter the numbers
10
12
17
45
80

The numbers arranged in descending order

80
45
17
12
10

The 2nd largest number is = 45
The 2nd smallest number is = 12
The average of 2nd largest & 2nd smallest is not in the array

Algorithm Given below is an algorithm to find the second largest and the second smallest numbers in an array −

Step 1 − Declare and read the number of elements.

Step 2 − Declare and read the array size at runtime.

Step 3 − Input the array elements.

Step 4 − Arrange numbers in descending order.

Step 5 − Then, find the second largest and second smallest numbers by using an index.

Step 6 − Print the second largest and the second smallest numbers.

Did you find this article valuable?

Support Elias Soykat by becoming a sponsor. Any amount is appreciated!