The program shows how to List Even Numbers within a Range in java. The program uses a scanner class to take the input of the last number(n) from the user.
Therefore it displays all the even numbers between 1 to n using for loop and if statement.
If you do not know the working process of for loop and if statement then click the link below.
Java Program to List all the Even Numbers within a Range
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 | //list even numbers using for loop import java.util.Scanner; public class ListOfEvenNumbers { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter the last number:"); int num = scanner.nextInt(); System.out.println("Displaying even numbers between 1 to " +num); for(int i=1; i <= num; i++) { // if the number is divisible by 2 then it is even if( i % 2 == 0) { System.out.print(i + " "); } } } } |
Output:
1 2 3 4 | Enter the last number: 50 Displaying even numbers between 1 to 50 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 |