Display all even numbers between 1 to 100 in java
In this article you can learn to write a java program that will display all the even numbers between 1 and 100 with 2 different approaches.
Approach:-1 "print all even numbers between 1 and 100 in java using for loop"
public class usingForLoop {
public static void main(String[] args){
System.out.println("Using For Loop");
for(int i = 1; i <= 100; i++)
{
if(i % 2 == 0)
{
System.out.print(i + " ");
}
}
}
}
In this program I have used for loop. Here I have fetched all the numbers from 1 to 100.
And in if statement, I have checked which numbers are even using modulus operator (%).
Now those numbers satisfy the even numbers condition i.e i % 2 == 0, has been printed.
Output
Approach:-2 "display even numbers between 1 and 100 in java using while loop"
public class usingWhileLoop {
public static void main(String[] args){
System.out.println("Using while loop");
int num = 2;
while(num <= 100)
{
System.out.print(num + " ");
num = num + 2;
}
}
}
In this approach I haven't use if condition, here I have simply added 2 to each numbers.
See if you add 2 to an even number, then the result number will be an even number.
- Ex:- 4 is even, now 4 + 2 = 6, here 6 also even number.
Here I have started the loop from 2 and at each iteration I am adding 2 to the new number.
Output
- - print all the ODD numbers between 1 to 100 using 2 approaches :- click