In this blog post, we will see, how to write a C Program to Print Even Numbers from 1 to N using a while and for a loop. We will also see how we can print even numbers from 1 to N without using a branching statement ( if-else statement).
C Program to Print Even Numbers from 1 to 100 using While Loop:
Below mentioned program is used to print even numbers from 1 to N using the while loop. The value of N is asked by users with the help of a scanf (input) function.
#include<stdio.h> int main() { int i = 2, number; printf("\n Please Enter the Maximum Limit Value : "); scanf("%d", &number); printf("\n Even Numbers between 1 and %d are : \n", number); while(i <= number) { printf(" %d\t", i); i = i+2; } return 0; }
Output:
Please Enter the Maximum Limit Value: 10
Even Numbers between 1 and 10 are :
2 4 6 8 10
C Program to Print Even Numbers from 1 to 100 using for Loop:
Below mentioned program is used to print even numbers from 1 to N using the for a loop. The value of N is asked by users with the help of a scanf (input) function.
#include<stdio.h> int main() { int i, number; printf("Please Enter the Maximum Limit Value : "); scanf("%d", &number); printf("Even Numbers between 1 and %d are : \n", number); for(i = 1; i <= number; i++) { if ( i % 2 == 0 ) { printf(" %d\t", i); } } return 0; }
Output:
Please Enter the Maximum Limit Value: 10
Even Numbers between 1 and 10 are :
2 4 6 8 10
C Program to Print Even Numbers from 1 to N without If Statement
#include<stdio.h> int main() { int i, number; printf("\n Please Enter the Maximum Limit Value : "); scanf("%d", &number); printf("\n Even Numbers between 1 and %d are : \n", number); for(i = 2; i <= number; i= i+2) { printf(" %d\t", i); } return 0; }
C Program to Print Even Numbers in a Given Range
Below mentioned C program allows the user to enter Minimum and maximum value. After that like the above-mentioned program, this C program will print even numbers in a given range.
#include<stdio.h> int main() { int i, min, max; printf("\n Please Enter the min Limit Value : "); scanf("%d", &min); printf("\n Please Enter the max Limit Values : "); scanf("%d", &max); if ( min % 2 != 0 ) { min++; } printf("\n Even Numbers between %d and %d are : \n", min, max); for(i = min; i <= max; i= i+2) { printf(" %d\t", i); } return 0; }
Output:
Please Enter the min Limit Value: 5
Please Enter the max Limit Values: 10
Even Numbers between 6 and 10 are :
6 8 10