C Program To Find Second Largest Number In An Array

c program to find second largest number in an array

Picture your list of numbers like a collection of candies, each with its own sweetness. Our journey into the world of C programming is like having a magical candy sorter. Now, think of this program as your candy sorter helping you find the second tastiest treat in your collection. It’s like having a friend who points out the second most delicious candy, making sure you savor every bit of sweetness. So, our “C program to find second largest number in an array” is your sweet-tooth companion, making sure you don’t miss out on the second-best flavor in your delightful array of candies! Ready for a tasty adventure? Let us immediately begin!

How to Find the Second Largest Number in an Array

Algorithm

1. Start
2. Initialize two variables, firstLargest and secondLargest, to the smallest possible integer value.
3. Input the size of the array.
4. Input the elements of the array.
5. Iterate through the array elements:
    a. If the current element is greater than firstLargest,
        i. Update secondLargest to firstLargest.
        ii. Update firstLargest to the current element.
    b. If the current element is greater than secondLargest but not equal to firstLargest,
        Update secondLargest to the current element.
6. Display the secondLargest as the result.
7. Stop

Pseudocode

Function findSecondLargest(arr):
    firstLargest = INT_MIN
    secondLargest = INT_MIN

    for each element in arr:
        if element > firstLargest:
            secondLargest = firstLargest
            firstLargest = element
        else if element > secondLargest and element != firstLargest:
            secondLargest = element

    return secondLargest

C Program To Find Second Largest Number In An Array

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

int main() {
    int size;

    // Retrieve the array size from the user input.
    printf("Enter the size of the array: ");
    scanf("%d", &size);

    // Validate that the size is positive
    if (size <= 0) {
        printf("Invalid array size. Please enter a positive integer.\n");
        return 1; // Exit with an error code
    }

    // Allocate memory dynamically for the array
    int *arr = (int *)malloc(size * sizeof(int));

    // Get array elements from the user
    printf("Enter each individual element of the array.: ");
    for (int i = 0; i < size; i++) {
        scanf("%d", &arr[i]);
    }

    // Find the largest and second largest numbers
    int firstLargest = INT_MIN;
    int secondLargest = INT_MIN;

    for (int i = 0; i < size; i++) {
        if (arr[i] > firstLargest) {
            secondLargest = firstLargest;
            firstLargest = arr[i];
        } else if (arr[i] > secondLargest && arr[i] != firstLargest) {
            secondLargest = arr[i];
        }
    }

    // Output the results
    printf("Largest = %d\n", firstLargest);
    printf("Second Largest = %d\n", secondLargest);

    // Free dynamically allocated memory
    free(arr);

    return 0;
}

This C program is designed to find the largest and second-largest elements in an array entered by the user. Here’s a detailed explanation of the code:

  1. User Input:
    • The program begins by prompting the user to enter the size of the array (size) they want to work with.
  2. Input Validation:
    • It checks if the entered size is a positive integer. If the size is less than or equal to zero, it prints an error message and exits the program with a non-zero return code.
  3. Dynamic Memory Allocation:
    • If the size is valid, the program dynamically allocates memory to store an array of integers (arr) using the malloc function.
  4. Array Input:
    • The user is then prompted to enter each element of the array. The program uses a loop to read these values from the user and stores them in the dynamically allocated array.
  5. Finding Largest and Second Largest:
    • The program initializes two variables, firstLargest and secondLargest, to the minimum possible integer value using INT_MIN from the limits.h header.
    • It then iterates through the array and compares each element with the current firstLargest and secondLargest values, updating them accordingly.
    • This logic ensures that the program finds the largest and second-largest elements in the array.
  6. Output:
    • Finally, the program prints the found values of the largest and second-largest elements.
  7. Memory Deallocation:
    • Before the program exits, it releases the dynamically allocated memory using the free function to prevent memory leaks.

Output/Complexity Analysis

The output will be the second largest number in the given array.

Enter the size of the array: 5

Enter the elements of the array: 110 2 45 7 63

Largest = 110

Second Largest = 63

Time Complexity: O(n), where n denotes the maximum size of the array.

Space Complexity: O(1), as only a constant amount of extra space is utilized.

Conclusion:

This tutorial explains how to use C programming to identify the second-largest integer in an array step-by-step. Large arrays can benefit from the algorithm’s efficiency and linear time complexity. It is easy to modify the given pseudo code and C implementation for a variety of uses where finding the second-largest entry in an array is necessary.

More on C Programming.

Leave a Reply

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