Home > Mobile >  C program to find the second largest element (also the largest)
C program to find the second largest element (also the largest)

Time:07-09

This is the code I wrote and I'm wondering if there is any solution for the way I am thinking(the second number should be < largest and also bigger than the previous number). Thanks and sorry for [duplicate] but I am really curious if there is anything similar.

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

int main() 
{
    int arr[10];
    int i;
    int greatest;
    int second;

    printf("Enter 10 values:");

    for (i = 0; i < 10; i  )
    {
        scanf("\n%d", &arr[i]);
    }

    greatest = arr[0];

    for (i = 1; i < 10; i  )
    {
        if (greatest < arr[i])
        {
            greatest = arr[i];
        }
    }

    second = arr[i];
    for (i = 0; i < 10; i  )
    {
        if (arr[i] < greatest && second > arr[i - 1])
        {
            second = arr[i];
        }
    }

    printf("The greatest number is : %d", greatest);
    printf("\nThe second greatest number is: %d", second);

    return 0;
}

CodePudding user response:

Your key mistake would be here:

   for (i = 1; i < 10; i  )
   {
       if (greatest < arr[i])
       {
           greatest = arr[i];
       }
   }

   second = arr[i];

Your loop conditions means that when the loops ends, i must be 10. That means arr[i] is out of bounds. This invokes undefined behavior. We have no way of knowing what the value of second is going into the next loop, and this will potentially affect your results.

You likely meant: second = arr[0] to initialize second with the first element in arr.

Having initialized second properly, you'd want to change that value only if the current element in the list is greater than the existing value for second and smaller than greatest.

In your code you've compared second to arr[i - 1]. When i is 0 on the first iteration, this will give you a negative index.

second = arr[0];

for (size_t i = 1; i < 10; i  ) {
    if (arr[i] < greatest && arr[i] > second) {
        second = arr[i];
    }
}

As a general suggestion, you do not need to declare your variables all at the beginning of the function in modern C. Declare them closer to actual use. Additionally, your i variables do not convey useful information beyond the scope of the loops, so scope them to the loops. That would have helped you catch the first out of bounds array access.

CodePudding user response:

The solution

#include <limits.h>
#include <stdio.h>

int main()
{
    int n = 5;
    int arr[n] = {1, 2, 3, 4, 5};
    int largest = INT_MIN, second = INT_MIN;

    for(int i = 0; i < n; i  )
    {
        if(arr[i] > largest)
        {
            second = largest;
            largest = arr[i];
        }
        else if(arr[i] > second && arr[i] != largest)
        {
            second = arr[i];
        }
    }

    printf("Largest: %d\nSecond: %d\n", largest, second);
}

Okay so here is the trick

When iterating through the array you have three cases.

The first case is that you have found a number greater than the largest number you have kept.

We attempt to initially keep the largest number at a minimum, hence the INT_MIN, so that any initial number that the array has will be within our scope. If we assume the initial largest number to be 0 then negative values wouldn't be considered at all and the program would fail if the array consisted of all negative numbers (an array with only 1 positive number would also fail since we also want the second largest).

If a greater number than the largest value is detected, we assign the largest value as the detected value. Since the former largest number is now the second-largest value we assign second to be largest. Hence

second = largest;
largest = arr[i];

The second case is that we have encountered a number that is not greater than the largest number that we currently hold but is greater than the second. Then we assign second to the said value hence:

second = arr[i];

The third case is that we have encountered a value that is neither larger than the larger nor larger than the second. We ignore the number if that is the case.

What is wrong with your code

The part that deals with the greatest number looks correct. However, the way that you set second to be arr[i] is wrong since i would be 10 here and arr[i] would be out of the bounds of the array. Also, you are iterating from 0 to 10 and checking arr[i-1] which is clearly unsafe.

CodePudding user response:

this should work

if(arr[1] > arr[0]){
    greatest = arr[1];
    second = arr[0];
}else{
    greatest = arr[0];
    second = arr[1];
}

for(int i=2;i<10;i  )
{
    if(second < arr[i]){
        if(greatest < arr[i]){
            second = greatest;
            greatest = arr[i];
        }
        else{
            second = arr[i];
        }
    }
}
  • Related