first with while loop
//program to print/display all even numbers lying between 1 to n natural numbers.
#include<stdio.h>
#include<conio.h>
void main()
{
int k=1,n;
printf("enter value of 'n'\n");
scanf("%d",&n);
while(k<=n)
{
if(k%2==0)
{ printf("%d,",k);
}
k++;
}
getch();
}
now with for loop
//program to print/display all even numbers lying between 1 to n natural numbers.
#include<stdio.h>
#include<conio.h>
void main()
{
int k,n;
printf("enter value of 'n'\n");
scanf("%d",&n);
for(k=1;k<=n;k++)
{
if(k%2==0)
{ printf("%d,",k);
}
}
getch();
}
now using do..while loop
//A program to print/display 1 to n natural numbers.
#include<stdio.h>
#include<conio.h>
void main()
{
int k=1,n;
printf("enter value of 'n'\n");
scanf("%d",&n);
do
{
if(k%2==0)
{
printf("%d,",k);
}
k++;
}
while(k<=n);
getch();
}
We can also use some other methods as shown below using different loop.
//program to print/display all even numbers lying between 1 to n natural numbers.
#include<stdio.h>
#include<conio.h>
void main()
{
int k=0,n;
printf("enter value of 'n'\n");
scanf("%d",&n);
while(k<=n)
{
printf("%d,",k);
k=k+2;
}
getch();
}
You now try same using other loops.