In this tutorial you will learn about the C Program to Print Second Largest & Second Smallest Array Element and its application with practical example.
C Program to Print Second Largest & Second Smallest Array Element
In this tutorial, we will learn to create a C program that will Print Second Largest & Second Smallest Array Element using C programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C programming topics:
- Operators in C Programming.
- Basic Input and Output function in C Programming.
- Basic C programming.
- For loop in C Programming.
Print Second Largest & Second Smallest Array Element:-
As we all know array is a collection of similar data type elements. In an array, only one variable is declared which can store multiple values. First will take the number of elements of an array from the user. Then will take the elements from the user for the array. And at last, Print Second Largest & Second Smallest Array Element using C Programming Language.
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 |
1. Declaring the variables for the program. 2. Taking the array size from the user. 3. Taking the elements of the array. 4. Sorting the array. 5. Printing the results. 6. End program. |
Program:-
Print Second Largest & Second Smallest Array Element
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
#include <stdio.h> int main() { //Declaring the variable. int n; int a[n]; //Declaration of array. //taking array size by the user. printf("Enter the number of elements:"); scanf("%d",&n); //taking array elements by the user printf("Enter the array elements :"); //taking input for the array for(int i=0;i<n;i++) { scanf("%d",&a[i]); } for(int i=0;i<n;i++) //Sorting The Array { int flag; for(int j=i+1; j<n ;j++) { if(a[i]<a[j]) { flag=a[i]; a[i]=a[j]; a[j]=flag; } } } printf("The second smallest element is %d",a[n-2]); //Accessing the smallest element printf("\n"); printf("The second largest element is %d",a[1]); //Accessing the largest element return 0; } |
Output:-
In the above program, we have first initialized the required variable
- a[n] = it will hold the elements in an array.
- n = it will hold the number of elements in an array.
- i = it will hold the integer value to control the array.
- flag = it will hold the integer value.
Taking input from the user in an array number of elements in the array.
Sorting the array,
Printing the results.