Home »
C programs »
C one-dimensional array programs
C program to find second largest element in a one dimensional array
In this article, we are going to write a C program to find the second maximum element from one dimensional array.
Submitted by Radib Kar, on December 04, 2018
Problem statement
Write a C program to find second largest element in a one dimensional array.
Example
Input :
arr[] = {10, 8, 7, 12, 14, 9}
Output :
Second largest element: 12
Input :
arr[] = {4, 6, 11, 10, 4}
Output :
Second largest element: 10
Finding second largest element in a an array
- Declare two variables first_large_ele and second_large_ele as int.
- Initialise both the variable with INT_MIN (i.e 0), first_large_ele = second_large_ele = 0.
-
Run for loop over array.
- if array[index] is greater than first_large_ele variable value then update the second_large_ele with first_large_ele variable value (i.e second_large_ele = first_large_ele) and assign array[index] value to first_large_ele variable (i.e first_large_ele = array[index]).
- if the array[index] is in between of first_large_ele and second_large_ele variable value then update the second_large_ele variable with array[index] (i.e econd_large_ele = array[index]).
- Return the second_large_ele.
C program to find second largest element in a one dimensional array
//
// main.c
// Second largest element in the array
//
// Created by Anshuman Singh on 22/06/19.
//
#include <stdio.h>
#include <stdlib.h>
int second_largest_element(int arr[], int length) {
int first_large_ele = 0, second_large_ele = 0, index;
if (length < 2) {
printf("Error: Array has less than two element !!!");
}
for (index = 0; index < length; index++) {
if (first_large_ele < arr[index]) {
second_large_ele = first_large_ele;
first_large_ele = arr[index];
}
else if (arr[index] != first_large_ele && \
second_large_ele < arr[index] && \
second_large_ele < first_large_ele) {
second_large_ele = arr[index];
}
}
return second_large_ele;
}
int main() {
int size, index;
printf("Enter the size of array: ");
scanf("%d", &size);
int arr[size];
int array_length = (int)sizeof(arr) / sizeof(int);
printf("\nEnter the array elements: ");
for (index = 0; index < array_length; index++) {
scanf("%d", &arr[index]);
}
printf("Second largest element: %d ", second_largest_element(arr, array_length));
return 0;
}
Output
Enter the size of array: 5
Enter the array elements: 11 22 44 55 33
Second largest element: 44
C One-Dimensional Array Programs »