All submissions

Find Maximum Element Using Pointer Walk

Code

#include <stdio.h>

int find_max_element(int *ptr, int n) {
    // Your logic here
    int max = *ptr;
    for(int i=1;i<n;i++)
    {
        ptr++;
        if(*ptr>max)
        {
            max = *ptr;
        }
    }
    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

Algorithm – Find Maximum Using Pointers

  1. Input the size of the array n and the array elements using pointer arithmetic (arr + i).
  2. Initialize a pointer ptr to the start of the array.
  3. Set max = *ptr (first element).
  4. Traverse the array using a loop:
    • Increment the pointer: ptr++
    • Compare *ptr with max
    • If *ptr > max, update max
  5. After traversal, print max.

 

 

Loading...

Input

5 10 25 5 30 15

Expected Output

30