49. Print Sum of Even Numbers

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>

int sum_even_numbers(int *ptr, int n) {
    int sum = 0;

    // int *arr = ptr;
    // int *end = ptr + n;

    // while(arr < end) {
    //     // Dereference to check the value, add to sum if even
    //     if(*arr % 2 == 0) {
    //         sum += *arr;
    //     }
    //     arr++; // Move pointer to the next integer in memory
    // }

    while(n > 0)
    {
        if(*ptr % 2 == 0) sum += *ptr;
        ptr++;
        n--;
    }
    
    // RETURN the final sum back to main()
    return sum; 
}

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

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

    // Call the function and store the returned value
    int result = sum_even_numbers(arr, n);

    // Print the final result here
    printf("Sum = %d\n", result);

    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote