C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Arrays in C

Find second smallest element

C Program: Find second smallest element

C

#include <stdio.h>

 

int main() {

    int arr[100], n, i;

    int first, second;

 

    // Input size of array

    printf("Enter number of elements in the array: ");

    scanf("%d", &n);

 

    // Input array elements

    printf("Enter %d elements:\n", n);

    for (i = 0; i < n; i++) {

        scanf("%d", &arr[i]);

    }

 

    // Initialize first and second smallest

    if (arr[0] < arr[1]) {

        first = arr[0];

        second = arr[1];

    } else {

        first = arr[1];

        second = arr[0];

    }

 

    // Find second smallest

    for (i = 2; i < n; i++) {

        if (arr[i] < first) {

            second = first;

            first = arr[i];

        } else if (arr[i] < second && arr[i] != first) {

            second = arr[i];

        }

    }

 

    printf("\nThe second smallest element is: %d\n", second);

 

    return 0;

}

Output

 
INPUT :
Enter number of elements in the array: 6
Enter 6 elements:
12 35 1 10 34 1

OUTPUT :
The second smallest element is: 10

Explanation

  1. The program first compares the first two elements to initialize first (smallest) and second (second smallest).
  2. It iterates through the remaining elements:
    • If a number is smaller than first, update both first and second.
    • If it’s greater than first but smaller than second, update second.
  3. Finally, it prints the second smallest number.