C program to print all even numbers between 1 to n using while loop

Write a C program to enter any number from user and print all even numbers between 1 to n using while loop. C program to display even number in a given range using while loop. How to generate even numbers from 1 to n using while loop in C programming.

Example

Input

Input value of n: 10

Output

Even numbers between 1 to 10: 2, 4, 6, 8, 10

Required knowledge

Basic C programming, If else, While loop

Before moving to this program you must know.

Read more - How to check whether a number is even or odd.

Program to print even numbers using if else

/**
 * 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("All even numbers from 1 to %d are: \n", n);

    /*
     * Starts loop counter from 1, increments by 1 till i<=n
     */
    i=1;
    while(i<=n)
    {
        /* Check even condition before printing */
        if(i%2==0)
        {
            printf("%d\n", i);
        }

        i++;
    }

    return 0;
}

Note: As I already mentioned the above method of generating even numbers is not optimal and takes more time to execute. Hence you must use the below method to generate even numbers.

Program to display even numbers without using if statement

/**
 * C program to display all even numbers from 1 to n using while loop
 */

#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);

    i=2; // Since 2 is the first even number
    while(i<=n)
    {
        printf("%d\n", i);

        /*
         * Adding 2 to current even number will give next even number
         */
        i += 2;
    }

    return 0;
}

Check this program using for loop.

Read more - Program to print all even numbers between 1 to n using for loop.

Output

Print all even numbers till: 100
All even numbers from 1 to 100:
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

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>