Topic-37:Finding 2nd largest number of an Array

To find the second largest number in an array using C language, you can follow a simple approach that involves iterating through the array to find the maximum element and then finding the maximum again while ignoring the first maximum.

Example:

#include <stdio.h>

 

#define MAX_SIZE 100

 

// Function to find the second largest number in an array

int findSecondLargest(int array[], int size) {

    int firstMax = array[0];  // Initialize firstMax to the first element

    int secondMax = array[0]; // Initialize secondMax to the first element

 

    // Find the first maximum element

    for (int i = 1; i < size; i++) {

        if (array[i] > firstMax) {

            secondMax = firstMax; // Update secondMax to previous firstMax

            firstMax = array[i];  // Update firstMax to the new maximum element

        } else if (array[i] > secondMax && array[i] != firstMax) {

            secondMax = array[i]; // Update secondMax if the current element is greater than the current secondMax

        }

    }

 

    return secondMax;

}

 

int main() {

    int arr[MAX_SIZE] = {2, 4, 6, 8, 10, 12, 14}; // Example array

    int size = 7; // Current size of the array

 

    // Call the findSecondLargest function to find the second largest number

    int secondLargest = findSecondLargest(arr, size);

 

    // Print the second largest number

    printf(“Second largest number: %d\n”, secondLargest);

 

    return 0;

}

 

    Explanation:

    • We have a function findSecondLargest that takes the array and its size as parameters.
    • Inside findSecondLargest, we initialize two variables firstMax and secondMax to the first element of the array.
    • We then iterate through the array to find the maximum element (firstMax). While doing so, we also update secondMax if we encounter a number greater than the current secondMax but not equal to firstMax.
    • Finally, we return secondMax, which represents the second largest number in the array.
    • In the main function, we define an example array arr and its size size.
    • We call the findSecondLargest function to find the second largest number in the array arr.
    • The second largest number is then printed.

    Leave a Comment

    Your email address will not be published. Required fields are marked *