Write C code to find maximum and second maximum in an array
Click for Solution

  • Warning: Illegal string offset 'name' in /home/prepdo6/gpl4you/discussquessub.php on line 681
    A #include<stdio.h>
    #include<conio.h>
    int size;
    main()
    {
    int a[size],i,j,k,n,l,m;
    n=2;
    printf("enter size of an array\n");
    scanf("%d",&size);
    printf("enter the elements of an array\n");
    for(i=0;i<size;i++)
    scanf("%d",&a[i]);
    while(n>0)
    {
    for(i=0;i<size;i++)
    {
    if(i==0)
    {
    j=a[i];
    k=a[i];
    }
    if(a[i]>j)
    {
    j=a[i];
    l=i;
    }
    if(a[i]<k)
    {
    k=a[i];
    m=i;
    }
    }
    printf("\n%d",j);
    a[l]=k;
    n--;
    }
    }



  • Warning: Illegal string offset 'name' in /home/prepdo6/gpl4you/discussquessub.php on line 681
    A Sorting is the best way to find the largest and second largest no in an array of any size
    ex: quick sort
    after performing the sorting
    directly printing the 1st and 2nd element in an array gives the answer....:)

    CpjJwWHV   Of course NOT sorting can be done in logn in best case,but this question can be solved in 2n only.
    12 years ago
    CpjJwWHV   void max(int *a)
    {
    int first_max, second_max;
    if(a[0]>a[1])
    {
    first_max=a[0];
    second_max=a[1];
    }
    else
    {
    first_max=a[1];
    second_max=a[0];
    }
    for(i=2;i<n;i++)
    {
    if(a[i]>second_max)
    {
    second_max=a[i];
    if(second_max>first_max)
    swap(second_max,first_max);
    }
    }
    printf("first_max=%d,second_max=%d",first_max,second_max);
    }
    12 years ago

    Smiley


  • Warning: Illegal string offset 'name' in /home/prepdo6/gpl4you/discussquessub.php on line 681
    A #include<stdio.h>
    #include<conio.h>
    int main()
    {
    int max1=0,max2=0,arr[100],n,i=0;
    printf("\n enter the number of elements: \n" );
    scanf("%d",

    CpjJwWHV   very bad approach... wenever changing the largest variable, add dis statement after dat
    slargest= largest; dis will automatically make slargest to second largest element.
    14 years ago

    Smiley

[Insert Code]