Topic-35:Find Min and Max

To find the minimum and maximum elements of an array in C language, you can iterate through the array once and keep track of the minimum and maximum elements encountered so far.

Example:

#include <stdio.h>

 

#define MAX_SIZE 100

 

// Function to find minimum and maximum elements of an array

void findMinMax(int array[], int size, int *min, int *max) {

    // Initialize min and max with the first element of the array

    *min = array[0];

    *max = array[0];

 

    // Iterate through the array to update min and max

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

        if (array[i] < *min) {

            *min = array[i];

        }

        if (array[i] > *max) {

            *max = array[i];

        }

    }

}

 

int main() {

    int arr[MAX_SIZE] = {7, 2, 9, 1, 5, 4, 8, 3, 6}; // Example array

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

    int min, max;

 

    // Call the findMinMax function to find min and max

    findMinMax(arr, size, &min, &max);

 

    // Print the min and max elements

    printf(“Minimum element: %d\n”, min);

    printf(“Maximum element: %d\n”, max);

 

    return 0;

}

 

    Explanation:

    • We have a function findMinMax that takes the array, its size, and two integer pointers (min and max) as parameters.
    • Inside findMinMax, we initialize min and max with the first element of the array.
    • Then, we iterate through the array starting from the second element and update min and max if we find a smaller or larger element respectively.
    • In the main function, we define an example array arr and its size size.
    • We declare variables min and max to store the minimum and maximum elements.
    • We call the findMinMax function to find the minimum and maximum elements of the array arr.
    • Finally, we print the minimum and maximum elements obtained.

    Leave a Comment

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