Q:

C program to print EVEN numbers from 1 to N using while loop

0

C program to print EVEN numbers from 1 to N using while loop

Given a range (value of N) and we have to print all EVEN numbers from 1 to N using while loop.

Example:

    Input:
    Enter value of N: 10

    Output:
    Even Numbers from 1 to 10:
    2 4 6 8 10

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to print EVEN numbers from 1 to N using while loop

#include <stdio.h>

int main()
{
	//loop counter declaration
	int number;
	//variable to store limit /N
	int n;

	//assign initial value 
	//from where we want to print the numbers
	number=1;

	//input value of N
	printf("Enter the value of N: ");
	scanf("%d",&n);

	//print statement
	printf("Even Numbers from 1 to %d:\n",n);

	//while loop, that will print numbers 
	while(number<=n)
	{
		//Here is the condition to check EVEN number
		if(number%2==0)
			printf("%d ",number);
		
		// increasing loop counter by 1
		number++;
	}

	return 0;
}

Output

Run(1)
Enter the value of N: 10 
Even Numbers from 1 to 10:
2 4 6 8 10 

Run(2)
Enter the value of N: 100 
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 

Another way to print EVEN numbers from 1 to N

Since, we know that EVEN numbers starts from 2 and EVEN numbers are those numbers which are divisible by 2. So, we can run a loop from 2 to N by increasing the value of loop counter by 2.

Consider the given code...

//initialising the number by 2
number=2;
//print statement
printf("Even Numbers from 1 to %d:\n",n);

//while loop, that will print numbers 
while(number<=n)
{
	//print the number 
	printf("%d ",number);
	//increase the value of number by 2
	number+=2;
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C program to print all uppercase alphabets using w... >>
<< C program to print ODD numbers from 1 to N using w...