Calculate Array Sum Using Only Pointers

Code

#include <stdio.h>

int calculate_sum(int *ptr, int n) {
    int Sum = 0;
    for(int i = 0; i < n; i++){
        Sum += *(ptr + i);
    }
    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;
}

Solving Approach

  • Input:
    Read n (number of elements) and then read n integers into the array.
  • Pass array to function:
    The array name arr is passed as a pointer ptr.
  • Traverse using pointer arithmetic:
    Loop through the array using *(ptr + i) to access each element.
  • Sum up values:
    Add each element to Sum.
  • Return and print:
    Return the total Sum from the function and print it in main().

 

 

Upvote
Downvote
Loading...

Input

5 1 2 3 4 5

Expected Output

15