All submissions

Calculate Array Sum Using Only Pointers

Code

#include <stdio.h>

int calculate_sum(int *ptr, int n) {
    // Your logic here
    int sum = 0;
    int* end = ptr + n;

    while(ptr < end){
        sum += *ptr;
        ptr++;
    }

    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

/*
Questions:
1. Pointer starts from start to the end of the arr
2. negative numbers?
3. n >= 1 ?
4. size of array <= 100
5. function just returns the sum?


Plan:
1. Pointer to traverse the array in a loop
2. Sum to a var by deref that pointer
3. Increment the pointer in the loop
*/

 

 

Loading...

Input

5 1 2 3 4 5

Expected Output

15