Java Program to print the following series. 2 4 6 8... n
Objective
Write a Java program to print the even number series 2, 4, 6, 8 ... N.
Algorithm / Approach
- Ask the user to input the maximum limit
N. - Read
nusing the Scanner class. - Start a
forloop withiinitialized to 2 (the first even number). - Check the condition
i ≤ n. - Print
i, then increment it by 2 in the loop update step (i = i + 2).
Test.java
import java.util.Scanner;
class Test {
public static void main(String[] a)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter N: ");
int n = s.nextInt();
for(int i = 2; i<=n; i=i+2) {
System.out.print(i+" ");
}
}
}
Expected Output
Enter N: 15 2 4 6 8 10 12 14
Explanation of the Program
- An even number is an integer divisible by 2.
- Instead of looping by 1 and using an
if (i % 2 == 0)check, this program optimizes the process by starting exactly at the first even number and stepping forward by 2. - This halves the total number of loop iterations required.
Complexity
Time Complexity
O(n/2) which simplifies to O(n)
Space Complexity
O(1)
Common Mistakes
- Using
i++in the loop header and forgetting to multiply by 2 inside the loop body, which would just print natural numbers instead.