Jun 3, 2020

C program to print Even number's from 1 to n

Ex: Write a C program to print even numbers between 1 to n. How to write a C program to print even numbers between 1 to n. C program to print even number's between 1 to n.


Input from user: 

Enter the limit: 20

Expected output:

Even numbers between 1 to 20:

2
4
6
8
10
12
14
16
18
20





Step by step logic to print even numbers between 1 to n(without using if-statement):


1. Accept limit from user store it in variable no.

2. Run for loop which iterate upto n number's. for(i=2;i<=no;i+=2)

3. We used i=2 because even number's starts from 2.

4.  We increment loop by two to print even numbers.

5. Print value of i inside the for loop.




Program to print even numbers without using if-statement:



#include<stdio.h>
int main()
{

int i,no;

printf("Enter the limit: ");
scanf("%d",&no);

printf("Even numbers between 1 to %d\n",no);

for(i=2;i<=no;i+=2)
{
printf("%d\n",i);

}

return 0;
}




Program to print even numbers using if-statement:

In below program we used if-statement to print even numbers from 1 to n.


#include<stdio.h>
int main()
{

 int i,no;

 printf("Enter the limit: ");
 scanf("%d",&no);

  printf("Even numbers between 1 to %d\n",no);

 for(i=1;i<=no;i++)
 {
   if(i%2==0)
   printf("%d\n",i);

 }

 return 0;
}



Above program's shows the following output:



Share This:    Facebook Twitter

0 comments:

Post a Comment

If you have any doubts, please discuss here...