/* */ Click to Join Live Class with Shankar sir Call 9798158723
Q.) WAP to to find second largest element in array With C program.
  

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

#define MAX_SIZE 1000   

int main()
{
    int arr[MAX_SIZE], size, i;
    int max1, max2;

    printf("Enter size of the array (1-1000): ");
    scanf("%d", &size);

    
    printf("Enter elements in the array: ");
    for(i=0; i< size; i++)
    {
        scanf("%d", &arr[i]);
    }

    max1 = max2 = INT_MIN;


    for(i=0; i< size; i++)
    {
        if(arr[i] > max1)
        {
           
            max2 = max1;
            max1 = arr[i];
        }
        else if(arr[i] > max2 && arr[i] < max1)
        {
            
            max2 = arr[i];
        }
    }

    printf("First largest = %d\n", max1);
    printf("Second largest = %d", max2);

   getch();
}
Output
Enter size of the array (1-1000): 10
Enter elements in the array: -7 2 3 8 6 6 75 38 3 2
First largest = 75
Second largest = 38

Program Explanation


Step 1 : Include header files (#include< stdio.h> and #include< conio.h>).

Step 2 : Start with main function with return type.

Step 3 : parenthesis to start and end the program { }.

Step 4 : declare variables with data type i.e, 'arr[MAX_SIZE],size, i' or 'max1, max2' is an integer type so we use "int" data type.

Step 5 : Use output function printf() to print the output on the screen.

Step 6 : Use input function scanf() to get input from the user.

Step 7 : here, we have find second largest element in array, Input size of the array then Input array elements and Check for first largest and second element, If current element of the array is first largest then make current max as second max and then max as current array element If current array element is less than first largest but is greater than second largest then make it second largest.

Step 8 : using getch() function to hold the screen.