java

Write a Program to Print Even Numbers From 1 to N

In this tutorial, we are going to see how to write a program to print even numbers from 1 to N.

In the following example, we print even numbers from 1 to N, the value of N we set here is 100, so the program will print even numbers between 1 and 100.

If an integer is exactly divisible by 2, which means that it leaves no remainder when divided by 2, then it is an even number. This same logic that we use here to find the even numbers. We start the loop from 1 to N and check each value if it is divisible by 2, if it is, we will print it.
 

 

Java Program to Print Even Numbers From 1 to N
public class Main {
	public static void main(String args[]) {
		int n = 100;
		System.out.println("Even numbers from 1 to "+n+" are: ");
		for (int i = 1; i <= n; i++) {
			if (i % 2 == 0) {
				System.out.println(i);
			}
		}
	}
}

Output:

Even numbers from 1 to 100 are:
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
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *