C program to find first two largest elements of an array

In this tutorial, you will learn how to write C program to find first two largest numbers in a given array.

Below are the approach which we will be follow to write our program:

  • In this program we will insert value in array.
  • Then we will iterate the array using for loop and compare elements till the end of array element. During comparison we will find the greatest two elements in a given array.
  • You can also follow a approach like first sort an array in decending order and then select top two distinct elements of an array.

How our program will behave?

As we have already seen above our logic to find the first two maximum number of a given array.

Our program will take an array as an input.

And on the basis of inputs and comparison it will print two greatest elements.

Program to find two largest number in an array

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void twoMax(int *arr,int size){
    int i,firstlargest=0,secondlargest=0;
    for(i=1;i<size;i++){
        if(arr[i]>firstlargest){
            secondlargest=firstlargest;
            firstlargest=arr[i];
        }
      }
    printf("%d and %d are top two maximum numbers",firstlargest,secondlargest);
}
void main(){
    int size,i,*arr;
    printf("Enter number of Elements in an array n");
    scanf("%d", &size);
    arr=(int*)malloc(sizeof(int)*size);
    printf("please enter the array elements n");
    for(i=0; i<size; i++){
        scanf("%d",&arr[i]);
    }
    twoMax(arr,size);
    getch();    
}
 

Output:

c program to find the largest two numbers in a given array

Explanation of above program to find first two maximum number of an array

  • In the above program we have taken two int variable size, i and one integer pointer variable arr to declare an array in main() method.
  • size variable will take the size of array given by user and arr will be array which size is calculated by malloc function dynamically at run time.
  • Now value will be assigned to each index of an array which is given by user using scanf() function of C.
  • We have a function called twoMax(arr,size) which will take array arr and size of array as an input.
  • The body of function twoMax(int *arr, int size) has all the logic of finding first two largest number of an array.
  • Method twoMax(int *arr, int size) have three variable i, firstlargest and secondlargest variable.
  • In initial we assuming first and second largest value is 0.
  •  for loop is to iterated the input array of twoMax method.
  • if statement inside for loop is to compare and calculate first and second largest value.

This was the concept to find program first and second largest value or we can say that top two maximum using C programming language.

Leave a Comment