Example
Input
Input upper range: 10
Output
Even numbers between 1 to 10: 2, 4, 6, 8, 10
/**
* C program to print all even numbers from 1 to n
*/
#include <stdio.h>
int main()
{
int i, n;
/* Input upper limit of even number from user */
printf("Print all even numbers till: ");
scanf("%d", &n);
printf("Even numbers from 1 to %d are: \n", n);
/*
* Start loop counter from 1, increment it by 1,
* will iterate till n
*/
for(i=1; i<=n; i++)
{
/* Check even condition before printing */
if(i%2 == 0)
{
printf("%d\n", i);
}
}
return 0;
}
Program to print even numbers without using if
statement
/**
* C program to display all even numbers from 1 to n without if
*/
#include <stdio.h>
int main()
{
int i, n;
/* Input upper limit of even number from user */
printf("Print all even numbers till: ");
scanf("%d", &n);
printf("All even numbers from 1 to %d are: \n", n);
/*
* Start loop from 2 and increment by 2,
* in each repetition
*/
for(i=2; i<=n; i+=2)
{
printf("%d\n",i);
}
return 0;
}
/*
Output :
Print all even numbers till: 100
All even numbers from 1 to 100 are:
2
4
6
8
10
12
14
16
18
20
22
24
26
28
30
32
34
36
38
40
42
44
46
48
50
52
54
56
58
60
62
64
66
68
70
72
74
76
78
80
82
84
86
88
90
92
94
96
98
100
*/