30. Print Sum of Even Numbers

#include <stdio.h>

// Function to find sum of even numbers using only pointer arithmetic
int sum_even_numbers(int *ptr, int n) {
    int sum = 0;

    for (int i = 0; i < n; i++) {
        if ((*(ptr + i)) % 2 == 0) { // Check if element is even
            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 = sum_even_numbers(arr, n);

    printf("Sum = %d", result);

    return 0;
}
  • We receive a pointer ptr pointing to the first element of the array.
  • Using a for loop, we move across the array using *(ptr + i) (pointer arithmetic, no indexing).
  • For each element:
    • Check if it is even using modulo operator (% 2 == 0).
    • If even, add it to a running sum.
  • Finally, we print the total sum of all even elements.

 

Loading...

Input

5 10 21 32 43 50

Expected Output

Sum = 92