Even number

Even numbers are numbers that have a difference of 2 unit or number. In other words, if the number is completely divisible by 2 then it is an even number.

Sum of N even numbers

This program is much similar to this one: Print all even numbers from 1 to N. The only difference is that instead of printing them we have to add it to some temporary variable and print it.

Logic

First, we declare one variable ” sum ” with value 0, and then we are going to use this variable to store sum of all even numbers between 1 to N. Now after taking input (N) from user, we have to check if the current variable “i” is even or not inside the loop . If it is even we have to add it to variable ” sum ” otherwise continue with the loop.

Once the loop is completed we have to print the variable ” sum “ containing the sum of all even numbers up to N.

Program

#include <stdio.h>

int main() {

    int i, n, sum = 0;

    // Take input from user.
    printf("Print sum of even numbers till : ");
    scanf("%d", &n);

    for(i = 1; i <= n; i++) {

        // Check for even or not.
        if((i % 2) == 0) {

            sum += i;

        }
    }

    printf("\nSum of even numbers from 1 to %d is : %d", n, sum);

    return 0;
}

Output

Print sum of even numbers till : 100
Sum of even numbers from 1 to 100 is : 2550