# Second Largest Element In Array In C Program

## Second Largest Element In Array In C Program

Write a C program to find largest and second largest element in an array.

In this program, you will learn how to find largest and second largest element in an array using for loop and if else condition.

Let's find the logic:

1. To find the second largest element we need to declare and ask user input for the array.

2. After this we need to create two variables for largest and second largest element, so that we can store the value in them, let's take max and secmax two variables.

3. Now we will use the minimum integer value for the two variables using <limit.h> & max=secmax=INT_MIN.

4. After this we will compare the elements, using iteration and if else condition. If the current element is greater than max then secmax will become max and max will become a[i]. i.e. max=secmax, max=a[i].

5. If the current element is smaller than max but greater than secmax then secmax will become a[i]. i.e. secmax = a[i].

Code

``#include <stdio.h>#include <limits.h> // For INT_MINint main(){    int arr[10], size, i;    int max, secmax;    /* Enter size of the array */    printf("Enter size of the array: ");    scanf("%d", &size);    /* Enter array elements */     printf("Enter elements in the array: ");    for(i=0; i<size; i++)    {        scanf("%d", &arr[i]);    }    max = secmax = INT_MIN;    /*    Check for first largest and second element     */    for(i=0; i<size; i++)    {        if(arr[i] > max)        {            secmax = max;            max = arr[i];        }        else if(arr[i] > secmax && arr[i] < max)        {            secmax = arr[i];        }    }    printf("First largest = %d\n", max);    printf("Second largest = %d", secmax);    return 0;}``

Output

``Enter size of the array: 3Enter elements in the array: 132First largest = 3Second largest = 2``