Print Alternate Numbers in Java

Print Alternate Numbers in Java explores a fundamental programming task: generating and displaying alternate numbers in Java. This blog navigates through essential concepts and provides practical examples to help developers understand and implement this functionality effectively.

Understanding the Problem 

The objective is to print a sequence of numbers, but only those at even-numbered positions (0-based indexing) within a specified range. For example, given a range from 1 to 10, the output should be:

1 3 5 7 9

Method to Print Alternate Numbers in Java

Here are some variations to consider:

  • Starting from a specific number (not necessarily 1).
  • Printing a specific number of alternate elements.
  • Printing in descending order.

This blog will address these variations with the presented solutions.

Approach 1: Using a for loop with conditional statement

The most straightforward approach utilizes a for loop and a conditional statement within the loop body. Here’s the code:

//Print Alternate Numbers in Java
public class PrintAlternateNumbers {

    public static void main(String[] args) {
        int start = 1;
        int end = 10;

        // Print alternate numbers in ascending order
        System.out.println("Printing alternate numbers from " + start + " to " + end + ":");
        for (int i = start; i <= end; i++) {
            if (i % 2 != 0) { // Check if odd (not divisible by 2)
                System.out.print(i + " ");
            }
        }
    }
}

Explanation of the Code:

  1. The code defines two variables, start and end, to represent the beginning and ending values of the range.
  2. A for loop iterates through the numbers from start to end (inclusive).
  3. Inside the loop, an if statement checks if the current number (i) is odd using the modulo operator (%). If the remainder after division by 2 is not zero (odd), the number is printed.
  4. The output displays “Printing alternate numbers from…” followed by the range. Inside the loop, each printed number is followed by a space.

Know How to Print ASCII Value in Java, Here!

Output:

Printing alternate numbers from 1 to 10:
1 3 5 7 9 

Print Alternate Numbers in Java Using a for loop with increment by 2

This approach optimizes the previous solution by focusing only on odd numbers. The loop increments by 2, ensuring we only encounter odd values within the desired range.

//Print Alternate Numbers in Java
public class PrintAlternateNumbersOptimized {

    public static void main(String[] args) {
        int start = 1;
        int end = 15;

        // Print alternate numbers in ascending order (optimized)
        System.out.println("Printing alternate numbers from " + start + " to "  + end + " (optimized):");
        for (int i = start; i <= end; i += 2) {
            System.out.print(i + " ");
        }
    }
}

Explanation of the code:

  1. Similar to the previous approach, variables start and end define the range.
  2. The for loop iterates, but with an increment of 2 in the loop condition (i += 2). This ensures the loop only considers odd numbers within the range.
  3. Inside the loop, the current odd number (i) is directly printed.

Output:

Printing alternate numbers from 1 to 15 (optimized):
1 3 5 7 9 11 13 15 

Print Alternate Numbers in Java Using recursion

While recursion might not be the most efficient approach for this specific task, it offers an alternative way to solve the problem and helps with understanding recursion concepts.

//Alternate numbers in Java
public class PrintAlternateNumbersRecursive {

    public static void printAlternate(int start, int end) {
        if (start > end) {
            return; // Base case: stop when start exceeds end
        }

        System.out.print(start + " ");
        printAlternate(start + 2, end); // Recursive call for next odd number
    }

    public static void main(String[] args) {
        int start = 1;
        int end = 17;

        // Print alternate numbers in ascending order (recursive)
        System.out.println("Printing alternate numbers from " + start + " to " + end + " (recursive):");
        printAlternate(start, end);
    }
}

Explanation of the code:

  1. The printAlternate method takes two integers, start and end, representing the range.
  2. A base case checks if start is greater than end. If so, the recursion stops as we’ve exceeded the desired range.
  3. If not at the base case, the current start (odd number) is printed.
  4. The method then calls itself recursively, passing start + 2 as the new starting point for the next odd number within the range. This continues until the base case is reached.

Also Learn How to Print Patterns in Java, Now!

Output:

Printing alternate numbers from 1 to 17 (recursive):
1 3 5 7 9 11 13 15 17 

Variations and Enhancements

The provided approaches can be adapted to handle different scenarios:

  1. Starting from a specific number: Modify the initial value of start in the loop or recursive call.
  2. Printing a specific number of alternate elements: Set a counter variable within the loop and break out after printing the desired number of elements.
  3. Printing in descending order: Reverse the loop condition (i >= start) or use a while loop that decrements.

By combining these techniques and understanding their trade-offs, you can effectively print alternate numbers in Java for various requirements.

In this blog, we explored the concept of printing alternate numbers in Java, enhancing both educational and practical skills. Experimentation is key; dive into coding and embrace the learning journey. Newtum offers an array of user-friendly tutorials across various programming languages. Keep coding, stay curious, and enjoy the process!

FAQ on How to Print Alternate Numbers in Java

Can I print alternate numbers in Java starting from a specific value?

Yes, you can modify the starting value in the loop or recursive call accordingly.

How do I print alternate numbers in Java in descending order?

Reverse the loop condition or use a while loop with decrements.

Are there variations to printing alternate numbers in Java?

Yes, you can print a specific number of elements or handle different starting points.

What if I want to print alternate numbers in reverse order?

Reverse the loop condition or use a while loop with decrements.

Can I use recursion for printing alternate numbers in Java?

Yes, recursion offers an alternative method, though it may be less efficient for larger ranges.

About The Author

Leave a Reply