Home > Back-end >  How to print second largest number in an array using C?
How to print second largest number in an array using C?

Time:12-16

I am new in C and i have been struggling to find the second largest index value. the program:

#include<stdio.h>
int main(){
    int i,max=0,smax=0;
    int A[] = {2,44,6,8,9,10,47};
    int n=5;
    for(i=1;i<n;i  ){
        if(A[max]<A[i]){
            smax=max;
            max=i;
        }
        else if(A[max]>A[i]){
            smax=i;
        }
    }
    printf("First value: %d\n",A[max]);
    printf("Second value: %d",A[smax]);
    return 0;
}

Now when i run the program,it is showing me this:

First value: 44
Second value: 9

What should i do to fix this?

CodePudding user response:

Given the presence of other answers, it may seem glib, but you could simply sort your array in descending order and then pick the second element.

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

int int_cmp_desc(const void *a, const void *b) {
    int x = *(int *)a;
    int y = *(int *)b;

    return x == y ? 0 :
           x <  y ? 1 : -1;
}

int main(void) {
    int A[] = {2,44,6,8,9,10,47};
    size_t sz = sizeof(A) / sizeof(*A);
    int B[sz];

    memcpy(B, A, sizeof(A));
    qsort(B, sz, sizeof(*B), int_cmp_desc);
    printf("%d\n", B[1]);

    return 0;
}

Of course, if you need the second largest unique number, this will make that easier too.

int main(void) {
    int A[] = {2,44,6,8,9,10,47,47};
    size_t sz = sizeof(A) / sizeof(*A);
    int B[sz];

    memcpy(B, A, sizeof(A));
    qsort(B, sz, sizeof(*B), int_cmp_desc);
    printf("%d\n", B[1]);

    int first_number = B[0];
    size_t i = 1;
    while (B[i] == first_number) i  ;

    printf("%d\n", B[i]);

    return 0;
}

Prints:

47
44

CodePudding user response:

To fix the issue in your program, you need to update the value of n to the correct length of the array A. Currently, n is set to 5, which means that the loop will only iterate over the first 5 elements of the array. As a result, the second largest value in the array is not being correctly identified.

To fix the issue, you can update the value of n like this:

int n = sizeof(A) / sizeof(A[0]);

This code calculates the length of the array by dividing the size of the entire array (in bytes) by the size of a single element in the array.

With this change, the program should output the correct values for the first and second largest elements in the array:

First value: 47
Second value: 44

Edited

he solution I provided earlier will not work if the array ends with a smaller value than the current second maximum value. To handle this case, you can add an additional check after the loop to ensure that the second maximum value is updated if needed.

int i, max = 0, smax = 0;
int A[] = {2, 44, 6, 8, 9, 10, 47};
int n = sizeof(A) / sizeof(A[0]);

for (i = 1; i < n; i  ) {
  if (A[max] < A[i]) {
    smax = max;
    max = i;
  } else if (A[smax] < A[i]) {
    smax = i;
  }
}

// Check if the second maximum value needs to be updated
if (A[smax] < A[max - 1]) {
  smax = max - 1;
}

printf("First value: %d\n", A[max]);
printf("Second value: %d", A[smax]);

CodePudding user response:

In my solution, I first initialize max and smax by looking only at the first two elements of the array. Afterwards, I check all remaining array elements to determine whether any of them is larger than smax. If I find one that is larger than smax, I check whether it is also larger than max, and act accordingly.

#include <stdio.h>
#include <stdlib.h>

int main( void )
{
    int max, smax;

    int A[] = { 2, 44, 6, 8, 9, 10, 47 };

    //set n to length of array
    const int n = sizeof A / sizeof *A;

    //make sure that the array has at least two values
    if ( n < 2 )
    {
        fprintf( stderr, "Array must contain at least two values!\n" );
        exit( EXIT_FAILURE );
    }

    //initialize max and smax by processing the first two
    //elements of the array
    if ( A[0] > A[1] )
    {
        max  = 0;
        smax = 1;
    }
    else
    {
        max  = 1;
        smax = 0;
    }

    //process the remaining elements of the array
    for( int i = 2; i < n; i   )
    {
        if ( A[i] > A[smax] )
        {
            if ( A[i] > A[max] )
            {
                smax = max;
                max = i;
            }
            else
            {
                smax = i;
            }
        }
    }

    //print the results
    printf( "Highest value: %d\n", A[max] );
    printf( "Second-highest value: %d", A[smax] );

    return EXIT_SUCCESS;
}

This program has the following output:

Highest value: 47
Second-highest value: 44
  •  Tags:  
  • c
  • Related