Basic

Switch Case

Goto

Operators

if Statement

Nested if

While Loop

For Loop

Patterns

Array

2D Array

String Function Example

Pointers

Recursion Function

Structure

Excersises

Others


Find the Largest and Smallest Number in an Array in C


Write a C program to find the largest and smallest number in an array.

  • Takes the size of the array and inputs its elements from the user.
  • Initializes both max and min with the first array element.
  • Traverses the array to update max and min by comparing each element.
  • Prints the largest and smallest elements found in the array.
Example : pgm.c
#include <stdio.h>

int main() {
    int n, i;
    int arr[100];
    int max, min;

    // Input array size
    printf("Enter the 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 max and min with the first element
    max = min = arr[0];

    // Traverse the array to find max and min
    for(i = 1; i < n; i++) {
        if(arr[i] > max) {
            max = arr[i];
        }
        if(arr[i] < min) {
            min = arr[i];
        }
    }

    // Output the results
    printf("Largest element: %d\n", max);
    printf("Smallest element: %d\n", min);

    return 0;
}

Output:

Enter the number of elements in the array: 4
Enter 4 elements:
5
8
6
2
Largest element: 8
Smallest element: 2