Find the Largest and Smallest Number in an Array in C

Arrays are a fundamental data structure in C, used to store multiple values of the same type in a single variable. Often, we need to determine the largest or smallest element in an array for data analysis, sorting, or other operations.

This tutorial demonstrates how to find both the largest and smallest numbers in an array using simple C programs, along with the algorithm and example output.

Problem Statement

Write a C program to find the largest and smallest number in a given array of integers.

Algorithm

Step 1: Start the program.

Step 2: Declare an array to store the elements and variables to hold the largest and smallest numbers.

Step 3: Input the size of the array and the elements from the user.

Step 4: Initialize the largest and smallest variables with the first element of the array.

Step 5: Traverse the array using a loop and compare each element:

- If the current element is greater than the largest variable, update largest.

- If the current element is smaller than the smallest variable, update smallest.

Step 6: After the loop ends, print the largest and smallest numbers.

Step 7: End the program.

C Program to Find Largest and Smallest Number in an Array

C
Program to find largest and smallest numbers in an array
#include <stdio.h>

int main() {
    int n, i;
    int largest, smallest;

    printf("Enter the number of elements in the array: ");
    scanf("%d", &n);

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

    // Initialize largest and smallest
    largest = smallest = arr[0];

    // Traverse the array
    for(i = 1; i < n; i++) {
        if(arr[i] > largest)
            largest = arr[i];
        if(arr[i] < smallest)
            smallest = arr[i];
    }

    printf("Largest number = %d\n", largest);
");
    printf("Smallest number = %d\n", smallest);

    return 0;
}

Example Input/Output

Input:
Enter the number of elements in the array: 5
Enter 5 elements: 12 45 7 34 23

Output:
Largest number = 45
Smallest number = 7

Notes

- The program uses a single loop to traverse the array and find both the largest and smallest numbers, making it efficient.

- Initializing the largest and smallest variables with the first element ensures that the comparison works for all array sizes, including arrays with negative numbers.

- This program assumes the array has at least one element. Input validation can be added for robustness.

Conclusion

Finding the largest and smallest number in an array is a common task in C programming. By understanding this example, you can apply the same logic to more complex array problems, such as finding the second largest number, sum of extremes, or performing array-based analysis.