A2oz

How to Print Alternate Even Numbers in Java?

Published in Java Programming 1 min read

You can print alternate even numbers in Java using a simple loop and conditional statements. Here's how:

1. Using a for loop

public class AlternateEvenNumbers {
  public static void main(String[] args) {
    // Print alternate even numbers from 2 to 20
    for (int i = 2; i <= 20; i += 4) {
      System.out.println(i);
    }
  }
}

This code uses a for loop to iterate through the numbers from 2 to 20. The loop increments the counter (i) by 4 in each iteration, ensuring that only alternate even numbers are printed.

2. Using a while loop

public class AlternateEvenNumbers {
  public static void main(String[] args) {
    // Print alternate even numbers from 2 to 20
    int i = 2;
    while (i <= 20) {
      System.out.println(i);
      i += 4;
    }
  }
}

This code uses a while loop to achieve the same result. The loop continues as long as the counter (i) is less than or equal to 20. In each iteration, the current even number is printed, and the counter is incremented by 4.

3. Using a do-while loop

public class AlternateEvenNumbers {
  public static void main(String[] args) {
    // Print alternate even numbers from 2 to 20
    int i = 2;
    do {
      System.out.println(i);
      i += 4;
    } while (i <= 20);
  }
}

This code uses a do-while loop, which is similar to a while loop but guarantees at least one iteration. The code prints the initial even number (2) before checking the condition (i <= 20).

4. Using a for-each loop

public class AlternateEvenNumbers {
  public static void main(String[] args) {
    // Print alternate even numbers from 2 to 20
    int[] evenNumbers = {2, 6, 10, 14, 18};
    for (int number : evenNumbers) {
      System.out.println(number);
    }
  }
}

This code uses a for-each loop to iterate through an array of even numbers. It's a more concise way to print the numbers in a specific order.

These examples demonstrate different ways to print alternate even numbers in Java. You can choose the method that best suits your specific needs and coding style.

Related Articles