WAP to print all even number between 1 to n using while loop
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 value of n: 10
Output even numbers between 1 to 10: 2, 4, 6, 8, 10
Also do check this program using for loop - C program to print all even numbers between 1 to n using for loop.
Example:
Input value of n: 10
Output even numbers between 1 to 10: 2, 4, 6, 8, 10
Also do check this program using for loop - C program to print all even numbers between 1 to n using for loop.
Required knowledge
Basic C programming, If else, While loop
Even numbers
Numbers that are
exactly divisible by 2 are called as even numbers. Example: 2, 4, 6, 8, 10 are the
first 5 even numbers.
Before moving to this program you must know how to check whether a number is even or odd using if else.
Before moving to this program you must know how to check whether a number is even or odd using if else.
Program to print even
numbers using if
/**
* C program to print all even numbers from 1
to n
*/
#include <stdio.h>
int main()
{
int i, n;
//Reads the 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;
//Reads the 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;
}
Output
X=_
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
All even numbers from 1 to 100:
2
4
6
8
10
12
14
16
18
20
22
24
Comments
Post a Comment