C Online Compiler
Example: Find Min Max in Array (Using Pointers) in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Find Min Max in Array (Using Pointers) #include <stdio.h> int main() { // Step 1: Declare and initialize an array int arr[] = {12, 5, 89, 3, 27, 45, 9}; int n = sizeof(arr) / sizeof(arr[0]); // Calculate the number of elements // Step 2: Initialize min_val and max_val with the first element int min_val = arr[0]; int max_val = arr[0]; // Step 3: Declare a pointer and point it to the second element // The loop will go from the second element up to, but not including, the end int *ptr = arr + 1; // Points to arr[1] int *end_ptr = arr + n; // Points one past the last element // Step 4: Iterate using the pointer while (ptr < end_ptr) { // Step 5: Compare the value pointed to by ptr with min_val and max_val if (*ptr < min_val) { min_val = *ptr; } if (*ptr > max_val) { max_val = *ptr; } ptr++; // Move the pointer to the next element } // Step 6: Print the results printf("Array elements: "); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); printf("Smallest element: %d\n", min_val); printf("Largest element: %d\n", max_val); return 0; }
Output
Clear
ADVERTISEMENTS