Program to find largest and second largest number in array

i have searched many websites for this question.They are doing it by some different approach.
This code is just not giving output if i input first element of array as largest i.e. a[0].
i think some minor change is required.
can anyone please tell me......

include<stdio.h>

int main()
{
int a[10],n;
int largest1,largest2,i;

printf("enter number of elements you want in array");
scanf("%d",&n);
printf("enter elements");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
largest1=a[0];
for(i=0;i<n;i++)
{
if(a[i]>largest1)
{
largest1=a[i];
}
}
largest2=a[0];
for(i=1;i<n;i++)
{
if(a[i]>largest2 && a[i]<largest1)
largest2=a[i];
}
printf("First and second largest number is %d and %d ",largest1,largest2);
}

Comments

  • largest2 = a[1];

  • Ignore the above, too late to change it. The real answer below.

    Don't assign initial min/max values directly from input. Use arbitrary large/small number instead.

    largest1 = -99999;
    largest2 = -99999;
    

    And second for loop should have i=0

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion