52. Calculate Array Sum Using Only Pointers

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>

int calculate_sum(int *ptr, int n) {
    // METHOD-1:-
    int sum = 0;
    
    // 1. Start our pointer exactly at the beginning of the array
    int *arr = ptr; 
    
    // 2. Calculate the exact memory address where the array ends
    int *end = ptr + n; 

    // 3. Scan through the memory addresses
    while (arr < end) {
        
        // Dereference the pointer to get the value, and add it to our running total
        sum += *arr; 
        
        // Move the pointer forward by 1 integer block (4 bytes) in memory
        arr++; 
    }
    
     return sum;

    //METHOD-2:-
    // if(n == 0) return 0;
    // Add the current element (*arr) to the sum of the rest of the array
    // return *ptr + calculate_sum(ptr + 1, n - 1);

    //METHOD-3:-
    // int sum = 0;
    // for(int i=0; i<n; i++)
    // {
    //     (arr + i) calculates the exact memory address. 
    //     *(arr + i) dereferences it to grab the integer inside!
    //     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

 

 

 

Was this helpful?
Upvote
Downvote