Hi Readers, In this post, we are going to write a core Java Program to print Even numbers within a given range n.
First of all, you should know how to find an Even number and it is pretty simple, divide any number by 2 if the remainder is zero then it’s an Even number.
So let’s see the complete Java Program here:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
/** * * @author agur */ import java.util.Scanner; public class PrintEven { public static void main(String[] args){ int limit, i; //create a scanner object to get the input Scanner in = new Scanner(System.in); //get the limit from user System.out.print("Enter the limit:"); limit = in.nextInt(); //print the even numbers System.out.println("Even numbers:"); //loop till the limit for(i=1; i<=limit; i++){ //divide by 2 if remainder is 0 then it is an even number if(i % 2 == 0) System.out.println(i); } } } |
Read the inline comments to understand the logic.
The output of the above program:
1 2 3 4 5 6 7 8 |
Enter the limit:10 Even numbers: 2 4 6 8 10 BUILD SUCCESSFUL (total time: 1 second) |
ENJOY LEARNING!