C program to find second largest number in array

write a C program to print the second largest number in the array. In this C programming example, we are going to find the second largest number of an array

What is an array?

The array is just a list of similar datatype

for example a=[14,15,86,5,89,52] here all the elements are integer which denotes its an array

Algorithm to find second largest number in array

  • Include libraries and initializing main method and variables we needed
  • Take input from the user and creating an array
  • Performing logic to find the second largest element from the array
  • Print the output got from the logic

C program to find second largest number in array

#include<stdio.h>
#include<limits.h>
void main(){
int i,size,first,second;
printf("please enter the number of element you want:");
scanf("%d",&size);
int arr[size];
printf("enter elements :"); 
for(i=0;i<size;i++){
scanf("%d",&arr[i]);
}
first=second=INT_MIN;
for(i=0;i<size;i++){
if(arr[i]>first){
second=first;
first=arr[i];
}
else if (arr[i]>second&&arr[i]<first){
second=arr[i];
}
}
printf("the second largest element is %d",second);
}

Explanation of the Code

On-Line no:1  include standard input and output library

On-Line no:2 include a standard limit library for taking the useful methods and function

On-Line no:3 creating the main method with void as its datatype

On-Line no:4 initialize the required variables

On-Line no:5  taking input from the user how much size the array should have

On-Line no:6 using scanf to take input

On-Line no:7 now here we initialize the array with the size that the user has given

On-Line no:8 giving the command to start printing the element

On-Line no:9 using for loop to append that element in the array

On-Line no:10  using scanf method to append the values in the array

On-Line no:11 closing the scope of the for loop

On-Line no:12 as we import limit library we took the minimum values that can a variable hold and dump it into two variables named first and second

On-Line no:13  now running for loop to access each and every element one by one

On-Line no:14 checking the element is greater than the first one

On-Line no:15 if yes then swapped that value to the variable second

On-Line no:16   now the accessed  variable will be in  the variable first

On-Line no:17 closing the if conditions scope

On-Line no:18 now else if part begins and checks the accessed element if it is greater then second variable and the smaller then first variable

On-Line no:19 now dumping that element into the variable named second

On-Line no:20 closing scope of else if the condition

On-Line no:21 closing scope  of for loop

On-Line no:22 printing the output value which is our second largest element in the array

On-Line no:23 closing scope of the main method

Output

In this blog, we learned that how to create a program to find the second largest element in the array