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
findMinMaxthat takes the array, its size, and two integer pointers (minandmax) as parameters. - Inside
findMinMax, we initializeminandmaxwith the first element of the array. - Then, we iterate through the array starting from the second element and update
minandmaxif we find a smaller or larger element respectively. - In the
mainfunction, we define an example arrayarrand its sizesize. - We declare variables
minandmaxto store the minimum and maximum elements. - We call the
findMinMaxfunction to find the minimum and maximum elements of the arrayarr. - Finally, we print the minimum and maximum elements obtained.