Program to Display even numbers from 1 to n where n is user input value.

we will create a Java program to display even numbers from 1 to n where n is user input value. here we can use while Loop to display even numbers.

Using while Loop :-

  • Create Scanner class object to pass user input.
  • To read user int value from sc.nextInt() method.
  • We have declared a variable i and initialized it with 1.
  • Here While loop is iterate where i value is less than equal to user input n times.
  • In order to check the number i, we have divided the number by 2 if it does not leave any remainder, the number is even and the print statement prints that number i.
  • After printing each even number, the value if i is increased by 1.
				
					import java.util.Scanner;

public class EvenNumbers {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter the user input number:- ");
		int n = sc.nextInt();
		int i = 1;
		System.out.println("Even number are :- ");
		while (i <= n) {
			if (i % 2 == 0)
				System.out.print(i + " ");
			i++;
		}
	}
}
				
			

Output :-
Enter the user input number:-
15
Even number are :-
2 4 6 8 10 12 14