Check The Programming Section
In this program 3 user defined functions are used:
void input(int arr[], int var)
void print(int arr[], int var)
void getSecondLargest(int arr[], int var)
#include <stdio.h>
#define SIZE 100
void input(int arr[],int var){
printf("Enter items for the array::");
for(int i=0;i<var;i++){
scanf("%d",&arr[i]);
}
}
void print(int arr[],int var){
printf("The items of the array::");
for(int i=0;i<var;i++){
printf("%d ",arr[i]);
}
}
int getSecondLargest(int arr[],int var){
int max1 = arr[0];
int max2 = arr[0];
for(int i=1;i<var;i++){
if(arr[i]>max1){
max2 = max1;
max1 = arr[i];
}
else if(arr[i]>max2){
max2 = arr[i];
}
}
return max2;
}
int main()
{
int var;
int arr[SIZE];
printf("How many items you want to insert::");
scanf("%d",&var);
input(arr,var);
print(arr,var);
printf("\nThe Second Largest Element of the array is %d", getSecondLargest(arr,var));
return 0;
}
Initially arr[] is created with SIZE 100 inside the main(). The variable var is used to take an input as number of items of the array arr. Further var is passed as argument to all three functions and used inside the loop of these functions.
void input(int arr[], int var): is used to take input for the array.
void print(int arr[], int var): is used to print the items of the array.
Inside the getSecondLargest() function, two variables max1 and max2 is initialised to the first item of the array. Further, other items are compared with max1 and max2. If any item is found greater than max1, its value is assigned to max2 and the i-th item is assigned to max1 as max1 will have the first largest element.
if(arr[i]>max1){
max2 = max1;
max1 = arr[i];
}
If i-th item is less than max1, but greater than max2, then update max2 only.
else if(arr[i]>max2){
max2 = arr[i];
}
Initially, max1 and max2 is initialised to arr[0], which is 12. There after, subsequent items arr[i] is compared with max1 and max2.
11 is less than max1 and max2 both, so no chnage in max1 and max2.
15 is greater than max1, so update max2 as max1 and max1 as 15.
14 is less than max1, but greater than max2, so update max2 as 14.
13 is less than max1 and max2, so no chage in max1 and max2.