C Program to find two largest elements in a one dimensional array.

C Program to find two largest elements in a one dimensional array. 

#include<stdio.h>

#include<stdlib.h>

#include<limits.h>

void findTwoMax(int* a,int n)

{

int max=a[0]; //initialize max to first array element

int sec_max=INT_MIN,temp=0; //initialize max to first array element

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=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;

}

To find Largest element



Post a Comment

Previous Post Next Post