All submissions

Find Maximum Element Using Pointer Walk

Code

#include <stdio.h>

int find_max_element(int *ptr, int n) {
    // Your logic here
    // int result = *ptr;

    // for (int i = 0; i < n; i++)
    // {
    //     /* code */

    //     if (result < *((ptr + i))){
    //         result = *((ptr + i));          
    //     }
        
    // }

    // return result;

    int max = *ptr;        // Assume first element is the max
    int *end = ptr + n;    // Pointer to one past the last element

    while (ptr < end) {
        if (*ptr > max) {
            max = *ptr;
        }
        ptr++;  // Move to next element
    }

    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;
}

Solving Approach

This version walks the array using a pointer (`ptr`) and a limit
pointer (`end = ptr + n`). It compares and updates the max value
by dereferencing the current pointer at each step.

Why This Version is Preferred:
-------------------------------
✔️ Efficient Traversal:
   - Uses pointer increment (`ptr++`) instead of `ptr + i`
   - Avoids repeated address arithmetic per iteration

✔️ Readable and Clean:
   - Linear flow, clearly shows intent to walk through memory

✔️ Compiler-Friendly:
   - Easy for compiler to optimize into tight loop
   - Fewer temporary calculations or pointer math

✔️ Memory and Time Efficient:
   - Operates entirely in-place
   - Uses one pointer and one `int` variable for result

 

 

Loading...

Input

5 10 25 5 30 15

Expected Output

30