Problem Statement:
Write a C program to find the maximum and minimum elements in the array.
Program:
#include
// Function to find maximum and minimum elements
void findMaxMin(int arr[], int n, int *max, int *min) {
*max = *min = arr[0]; // Initialize max and min with the first element
// Traverse the array to update max and min
for (int i = 1; i < n; i++) {
if (arr[i] > *max)
*max = arr[i];
else if (arr[i] < *min)
*min = arr[i];
}
}
int main() {
int arr[] = {10, 5, 20, 8, 15};
int n = sizeof(arr) / sizeof(arr[0]);
int max, min;
findMaxMin(arr, n, &max, &min);
printf("Maximum element: %d\n", max);
printf("Minimum element: %d\n", min);
return 0;
}
Explanation:
- The
findMaxMin
function takes the array, its sizen
, and two pointers to integersmax
andmin
. - It initializes
max
andmin
with the first element of the array. - It then traverses the array and updates
max
andmin
accordingly. - In the
main
function, an array of integers is declared and initialized. - The size of the array is determined using
sizeof
. - The
findMaxMin
function is called with the array, its size, and pointers tomax
andmin
. - Finally, the maximum and minimum elements are printed.
Post a Comment