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
findMaxMinfunction takes the array, its sizen, and two pointers to integersmaxandmin. - It initializes
maxandminwith the first element of the array. - It then traverses the array and updates
maxandminaccordingly. - In the
mainfunction, an array of integers is declared and initialized. - The size of the array is determined using
sizeof. - The
findMaxMinfunction is called with the array, its size, and pointers tomaxandmin. - Finally, the maximum and minimum elements are printed.

إرسال تعليق