Home »
C programs »
C one-dimensional array programs
C program to find two largest elements in a one dimensional array
Here, we are implementing a C program that finds the two largest numbers from a one dimensional array.
Submitted by Radib Kar, on December 05, 2018
Problem statement
Write a C program to find two largest elements in a one dimensional array.
Examples
Example: Type1: (all the elements are not same & no of element is more than two)
Input:
Array size: 4
Elements: 32 54 -6 43
Output:
54 43
Example: Type2: (second maximum doesn’t exist as size of array < 2)
Input:
Array size : 1
Elements: 4
Output:
4
Example: Type3: (all elements are same, thus only one largest element)
Input:
Array size : 4
Elements: 12 12 12 12
Output:
12
Steps to find two largest elements in a an array
- Define two variable max & sec_max
- Initialize max to array[0] & sec_max to INT_MIN
- Scan the entire array
a. For(int i=0;i<n;i++)
if array[i]>max
then update max to array[i]&sec_max to previous max value
else if array[i] is greater than sec_max but less than max
then update sec_max to array value
do nothing to max
End for loop
- If still sec_max has the value INT_MIN
Only one largest value exists, print it
Else
Print max & sec_max
C program to find two largest elements in a one dimensional array
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
void findTwoMax(int* a, int n) {
// initialize max to first array element
int max = a[0];
// initialize max to first array element
int sec_max = INT_MIN, temp = 0;
for (int i = 0; i < n; i++) { // scan the entire array
// if a[i]> max then update max to array value &
// second max to previous max value
if (a[i] > max) {
sec_max = max;
max = a[i];
}
// else if a[i] is greater than second max but less
// than max then update second max to array value
else if (a[i] > sec_max && a[i] < max)
sec_max = a[i];
// do nothing to max
}
// if second max is still at its initialized value
// then no second maximum exists at all
if (sec_max == INT_MIN)
printf("only one large element: %d ", max);
else
printf("First largest element: %d & second largest element : %d", max,
sec_max);
}
int main() {
int n;
printf("enter no of elements\n");
scanf("%d", &n);
// dynamic array created
int* a = (int*) malloc(sizeof(int) * n);
printf("enter the elements........\n");
// taking input
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
// find two largest no
findTwoMax(a, n);
return 0;
}
Output
First run:
enter no of elements
4
enter the elements........
32 54 -6 43
First largest element: 54 & second largest element : 43
Second run:
enter no of elements
1
enter the elements........
4
only one large element: 4
Third run:
enter no of elements
4
enter the elements........
12 12 12 12
only one large element: 12
C One-Dimensional Array Programs »