Write a program that prints the even numbers from 1 to 20.
Program in C
C
#include <stdio.h>
int main() {
int i;
for (i = 2; i <= 20; i += 2) {
printf("%d\n", i);
}
return 0;
}
Explanation:
- In this program, we initialize i to 2 since it is the first even number within the desired range.
- The loop condition i <= 20 ensures that the loop continues until i reaches or exceeds 20.
- We increment i by 2 in each iteration using i += 2, which guarantees that i remains an even number.
Output:
Output
2
4
6
8
10
12
14
16
18
20
Program in Java
Java
public class EvenNumberPrinting {
public static void main(String[] args) {
for (int i = 2; i <= 20; i += 2) {
System.out.println(i);
}
}
}
Explanation:
- public class EvenNumberPrinting: This line declares a public class named EvenNumberPrinting.
- public static void main(String[] args): This is the main method that serves as the entry point of the program.
- for (int i = 2; i <= 20; i += 2) { … }: This is a for loop that initializes the loop counter i to 2, executes the loop body as long as i is less than or equal to 20, and increments i by 2 in each iteration.
- System.out.println(i);: This line prints the value of i followed by a newline character.
Output
2
4
6
8
10
12
14
16
18
20