Lets write a C program to find sum of all the even numbers from 1 to N, using for 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
For Loop In C Programming Language
Even or Odd Number: C Program
C Program To Find Even Numbers Between Range using For Loop
You can also watch the video for C Program To Find Sum of All Even Numbers From 1 To N, using While loop
Video Tutorial: C Program To Find Sum of All Even Numbers From 1 To N, using For loop
[youtube https://www.youtube.com/watch?v=HdvySOYOv9w]
Logic To Find Sum of All Even Numbers From 1 To N, using For loop
Since we are checking for even numbers from 1 to user entered number, we assign value of variable count to 1. For loop keeps iterating until value of count is less than or equal to value of user input number. For each iteration of for loop we increment the value of count by 1.
Inside for 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 for 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 For loop
#include<stdio.h> int main() { int count, num, sum = 0; printf("Enter the limit\n"); scanf("%d", &num); printf("Even numbers from 1 To %d are:\n", num); for(count = 1; count <= num; count++) { if(count % 2 == 0) { printf("%d\n", count); sum = sum + count; } } printf("Sum of even numbers from 1 To %d is %d\n", num, sum); return 0; }
Output 1:
Enter the limit
5
Even numbers from 1 To 5 are:
2
4
Sum of even numbers from 1 To 5 is 6
Output 2:
Enter the limit
10
Even numbers from 1 To 10 are:
2
4
6
8
10
Sum of even numbers from 1 To 10 is 30
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