C Program To Find Sum of All Even Numbers From 1 To N, using While loop


Lets write a C program to find sum of all the even numbers from 1 to N, using while loop.

Even Number: An even number is an integer that is exactly divisible by 2.

For Example: 8 % 2 == 0. When we divide 8 by 2, it give a reminder of 0. So number 8 is an even number.

If user enters num = 5. Even numbers between 1 to 5 are 2, 4. So we add 2 and 4. i.e., 2 + 4 = 6. We display 6 to the console window as result.

Related Read:
Decision Control Instruction In C: IF
while loop in C programming
Even or Odd Number: C Program
C Program to Generate Even Numbers Between Two Integers

Video Tutorial: C Program To Find Sum of All Even Numbers From 1 To N, using While loop


[youtube https://www.youtube.com/watch?v=EZeusHqc0Rc]

YouTube Link: https://www.youtube.com/watch?v=EZeusHqc0Rc [Watch the Video In Full Screen.]

Logic To Find Sum of All Even Numbers From 1 To N, using While loop

Since we are checking for even numbers from 1 to user entered number, we assign value of variable count to 1. While loop keeps iterating until value of count is less than or equal to value of user input number. For each iteration of while loop we increment the value of count by 1.

Inside while loop we check for the condition, count%2 == 0. If it’s true, then we add the value present inside variable count to previous value present in variable sum.

After the control exits while loop we display the value present in variable sum – which has the sum of all the even numbers from 1 to user entered number.

Source Code: C Program To Find Sum of All Even Numbers From 1 To N, using While loop

#include<stdio.h>

int main()
{
    int num, count = 1, sum = 0;

    printf("Enter the limit\n");
    scanf("%d", &num);

    while(count <= num)
    {
        if(count%2 == 0)
        {
            sum = sum + count;
        }
        count++;
    }
    printf("Sum of Even numbers from 1 to %d is %d\n", num, sum);
    return 0;
}

Output 1:
Enter the limit
5
Sum of Even numbers from 1 to 5 is 6

Output 2:
Enter the limit
20
Sum of Even numbers from 1 to 20 is 110

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Leave a Reply

Your email address will not be published. Required fields are marked *