- Lets see how to write a c program to print even numbers using c programming.\
- Its a basic example to print only even numbers
- Use for loop and iterate from 1 to n.
- In each iteration check if number if divisible by 2 (n%2 == 0). if yes then its a even number otherwise it is a odd number.
- C program to print even numbers from 1 to n.
- #include<stdio.h>
- //write a program to print even numbers in c
- //www.instanceofjava.com
- int main()
- {
- // declare variables
- int number,i;
- //read input from user
- printf("Enter a number: ");
- scanf("%d", &number);
- //iterate and check if it a even number or not
- for (i=1; i<=number; i++){
- if(i%2 ==0){
- printf("%d\n" ,i);
- }
- }
- getch();
- }
Output:
- Enter a number: 12
- 2
- 4
- 6
- 8
- 10
- 12
#2 print even numbers in c using while loop
- Now we will try to print even numbers using while loop
- Only difference is replace for with while loop
- Variable initialization will be done before loop
- condition will be inside while(condition)
- increment or decrement will be last line of while block
- Lets print even numbers using while loop from 1 to n.
- #include<stdio.h>
- //write a program to print even numbers in c using while loop
- //www.instanceofjava.com
- int main()
- {
- // declare variables
- int number,i;
- //read input from user
- printf("Enter a number: ");
- scanf("%d", &number);
- //iterate and check if it a even number or not
- i=1;
- while(i<=number){
- if(i%2 ==0){
- printf("%d\n" ,i);
- }
- i++ ;
- }
- getch();
- }
Output:
- Enter a number: 20
- 2
- 4
- 6
- 8
- 10
- 12
- 14
- 16
- 18
- 20
No comments