C program to find the largest and second-largest in an array

Last updated on 10th February 2023

This program finds the largest and second-largest elements in an array of integers. Here's a step-by-step explanation of the code:

  1. The preprocessor directive #define MAX 100 defines a constant MAX with the value 100, which sets the maximum number of elements in the array.

  2. The main function starts by defining the following variables:

    • largest variable will store the largest element in the array.

    • second_largest variable will contain the second largest element in the array.

    • a is an array of MAX elements, which will store the input array.

    • len is a variable that will store the number of elements in the array

  3. The program prompts the user to enter the number of elements in the array.

  4. If the number of elements is less than 2 then the program prints the message Array should have a minimum of 2 elements and exits.

  5. The program then prompts the user to enter the elements of the array and uses a for loop and scanf to read and store the input in the array a.

  6. largest is initialized to the first element of the array and second_largest to 0.

  7. The program then uses another for loop to iterate over the elements of the array. In each iteration, it checks if the current element is greater than largest. If it is, it updates second_largest to largest and largest to the current element. If not, it checks if the current element is greater than second_largest and not equal to largest. If it is, it updates second_largest to the current element.

  8. Finally, the program prints the largest and second-largest elements and returns.

Here is the C program.

#include <stdio.h>
#define MAX 100

int main() 
{
 int largest;
 int second_largest;
 int len;
 int a[MAX];
    
 // Read the array
 printf("Enter number of elements in the array ");
 scanf("%d", &len);

 if (len < 2)
 {
    printf("The array should have atleast 2 elements.");
    return;
 }
   
 printf("Enter array elements:\n");
 for (int i=0; i < len; i++)
    scanf("%d", &a[i]);

 largest = a[0];
 second_largest = 0;

 for(int i=0; i < len ; i++){
    if(a[i] > largest) {
        second_largest = largest;
        largest = a[i];
    }
    else if((a[i] > second_largest) && (a[i] != largest) ) {
          second_largest = a[i];      
    }
 }

 printf("Largest is %d
", largest);
 printf("Second largest is %d
", second_largest);

 return 0;
}

Sample output

Enter number of elements in the array 5
Enter array elements:
10 10 10 8 5
Largest is 10
Second largest is 8

Post a comment

Comments

Nothing yet..be the first to share wisdom.