Print Sum of Even Numbers

Code

#include <stdio.h>

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

Solving Approach

  • Input: Read n and n numbers into an array.
  • Pointer use: Pass the array pointer to the function.
  • Logic: In the function, loop through elements using pointer arithmetic.
    • If the number is even (*(ptr + i) % 2 == 0), add it to Sum.
  • Return: Send back the total Sum to main().
  • Output: Print the result.

 

 

Upvote
Downvote
Loading...

Input

5 10 21 32 43 50

Expected Output

Sum = 92