C Online Compiler
Example: Find Min Max using Pointers in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Find Min Max using Pointers #include <stdio.h> int main() { // Step 1: Declare and initialize an array int arr[] = {12, 5, 8, 20, 3, 15, 7}; int n = sizeof(arr) / sizeof(arr[0]); // Calculate the number of elements // Step 2: Declare pointer variables int *ptr = arr; // Pointer to the first element int *end_ptr = arr + n; // Pointer to one past the last element // Step 3: Initialize min_val and max_val with the value at the first element int min_val = *ptr; int max_val = *ptr; // Step 4: Move pointer to the second element for iteration ptr++; // Step 5: Iterate through the array using the pointer while (ptr < end_ptr) { // Step 6: Compare value pointed to by ptr with min_val if (*ptr < min_val) { min_val = *ptr; } // Step 7: Compare value pointed to by ptr with max_val if (*ptr > max_val) { max_val = *ptr; } // Step 8: Move to the next element ptr++; } // Step 9: Print the results printf("Array elements: "); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); printf("Minimum element: %d\n", min_val); printf("Maximum element: %d\n", max_val); return 0; }
Output
Clear
ADVERTISEMENTS