32. Find Maximum Element Using Pointer Walk

#include <stdio.h>

// Function to find maximum element using only pointer arithmetic
int find_max_element(int *ptr, int n) {
    int max = *ptr; // Initialize max with first element

    for (int i = 1; i < n; i++) {
        if (*(ptr + i) > max) {
            max = *(ptr + i); // Update max if current element is greater
        }
    }

    return max;
}

int main() {
    int n;
    scanf("%d", &n);

    int arr[100];
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    int result = find_max_element(arr, n);
    printf("%d", result);

    return 0;
}
  • Initialize max with the value pointed by ptr (first element).
  • Move the pointer using *(ptr + i) and compare each value with max.
  • If a larger value is found, update max.
  • After traversing all elements, return the max value.

 

Loading...

Input

5 10 25 5 30 15

Expected Output

30