Summary: This program takes an array of integers, traverses it using pointers, and finds the largest and smallest elements.
#include <stdio.h>
void findMinMax(int *arr, int size, int *min, int *max) {
*min = *arr;
*max = *arr;
for (int i = 1; i < size; i++) {
if (*(arr + i) < *min) {
*min = *(arr + i);
}
if (*(arr + i) > *max) {
*max = *(arr + i);
}
}
}
int main() {
int n, min, max;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d integers: ", n);
for (int i = 0; i < n; i++) {
scanf("%d", arr + i);
}
findMinMax(arr, n, &min, &max);
printf("\nLargest element: %d\n", max);
printf("Smallest element: %d\n", min);
return 0;
}
Pointer Initialization:
The function findMinMax() initializes *min and *max to the first element of the array.
Pointer Arithmetic:
The array is traversed using pointer arithmetic, comparing each element to update the min/max values.
Function Usage:
The function is called with the array, size, and addresses of min and max to update the values dynamically.
Array Input and Output:
The array elements are entered by the user, and the largest and smallest elements are printed after finding them.