Any number divisible by 2 is an even number. Here we will see a writing program using a while loop to print all even numbers between 1 and 100.
When we divide the number by 2 we will get the remainder zero which is the property of an even number.
Steps:
- In the below Program, we are starting iteration with 1 and checking its divisibility by 2 in the if block.
- If the condition is satisfied, we print it and in both scenarios, we are incrementing the number by 1.
- For eg . 3%2 = 1, which does not satisfy our if condition and hence skips the printing and directly increments it. Now the number will become 4 after incrementing 1.
Java Program to print even numbers between 1 to 100 using while loop
import java.util.*;
public class Main
{
public static void main(String args[])
{
int start = 1;
int end = 100;
System.out.println("Even numbers between "+ start+ " and " +end+ " are :");
while(start<=end) {
if(start%2 == 0) {
System.out.println(start);
}
start++;
}
}
}
Output
Even numbers between 1 and 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