C program to find sum of even numbers between 1 to n

Write a C program to enter any number from user and find the sum of all even numbers between 1 to n. How to find sum of even numbers in a given range using loop in C programming. Logic to find sum of even numbers in a given range in C program.

Example

Input

Input upper limit of even number: 10

Output

Sum of even numbers between 1 to 10: 30

Required knowledge

Basic C programming, For loop

Must read - Program to print even numbers in a given range

Logic to find sum of even number

Below is the step by step descriptive logic to find sum of even numbers.

  1. Input upper limit to find sum of even number. Store it in some variable say N.
  2. Initialize another variable that will hold our sum with 0 say sum = 0.
  3. Initialize a loop from 2 to N and increment 2 on each iteration. The loop structure should look like for(i=2; i<=N; i+=2).
  4. Inside the loop body add the previous value of sum with i i.e. sum = sum + i.
  5. After the loop print the final value of sum.

Program to find sum of even numbers

/**
 * C program to print sum of all even numbers between 1 to n
 */

#include <stdio.h>

int main()
{
    int i, n, sum=0;

    /* Input upper limit from user */
    printf("Enter upper limit: ");
    scanf("%d", &n);

    for(i=2; i<=n; i+=2)
    {
        /* Add current even number to sum */
        sum += i;
    }

    printf("Sum of all even number between 1 to %d = %d", n, sum);

    return 0;
}

Note: sum += i is similar to sum = sum + i. You can use any of them to find sum.

Output

Enter upper limit: 10
Sum of all even number between 1 to 10 = 30

Program to find sum of even numbers in given range

/**
 * C program to print sum of all even numbers in given range
 */

#include <stdio.h>

int main()
{
    int i, start, end, sum=0;

    /* Input lower and upper limit from user */
    printf("Enter lower limit: ");
    scanf("%d", &start);
    printf("Enter upper limit: ");
    scanf("%d", &end);


    // If start is not even then make it even
    if(start%2!=0)
    {
        start++;
    }

    for(i=start; i<=end; i+=2)
    {
        /* Add current even number to sum */
        sum += i;
    }

    printf("Sum of all even number between %d to %d = %d", start, end, sum);

    return 0;
}

Output

Enter lower limit: 6
Enter upper limit: 10
Sum of all even number between 6 to 10 = 24

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>