33. Calculate Array Sum Using Only Pointers

#include <stdio.h>

// Function to calculate sum of array elements using only pointer arithmetic
int calculate_sum(int *ptr, int n) {
    int sum = 0;

    for (int i = 0; i < n; i++) {
        sum += *(ptr + i); // Add each element to sum
    }

    return sum;
}

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

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

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

    return 0;
}
  • Start with sum = 0.
  • Traverse the array by moving the pointer using ptr + i.
  • Dereference each pointer and add the value to sum.
  • After the full walk, return the accumulated sum.
Loading...

Input

5 1 2 3 4 5

Expected Output

15