Java Program to Print Odd Numbers From 1 to 100

In this blog, we will explore different methods to print odd numbers from 1 to 100 in Java. Understanding these techniques will not only help you solve this specific problem but also improve your overall coding skills. Printing odd numbers is a common programming task that involves generating a sequence of numbers and displaying only those that are odd.

Importance of Learning How to Print Odd Numbers from 1 to 100 in Java

Furthermore, learning how to print odd numbers from 1 to 100 in Java is essential for strengthening coding skills and problem-solving abilities. Understanding this fundamental task allows programmers to filter data, perform mathematical computations, and solve various programming challenges efficiently. Mastery of iterative and functional approaches not only empowers developers to work with collections effectively but also boosts their comprehension of loop structures and functional programming features in Java. Additionally, exploring alternative methods and best practices enhances code readability and maintainability. This knowledge broadens horizons in Java programming, enabling developers to tackle complex tasks and contribute effectively to software development projects.

In this blog, we will cover two primary approaches to print odd numbers: the iterative approach using for and while loops and the functional approach utilizing Java 8’s Stream API and lambda expressions. We will also discuss best practices and handle edge cases to ensure a robust solution.

What is an Odd Number?

Odd numbers are integers that cannot be divided by 2 without leaving a remainder. In other words, odd numbers are those whose last digit is 1, 3, 5, 7, or 9.

Characteristics of Odd Numbers

      1. Every odd number can be expressed in the form 2n + 1, where n is an integer.

      2. Even numbers are always the sum of two odd numbers.

      3. Furthermore, the product of two odd numbers is always odd.

Examples of Odd Numbers

Below are some examples of odd numbers: 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99, and so on.

Program to Print Odd Number Using Java for Loop

// Print Odd Numbers From 1 to 100 in Java

class oddNumEx {
   public static void main(String args[]) {
	int num = 100;
	System.out.print("Odd Numbers from 1 to "+num+" are: ");
	for (int i = 1; i <= num; i++) {
	   if (i % 2 != 0) {
		System.out.print(i + " ");
	   }
	}
   }
}

Explanation of the code
The given code is a Java program to print odd numbers from 1 to 100. Here’s a comprehensive explanation of the code’s functioning

1. `class oddNumEx`: This line declares a new Java class named `oddNumEx`.

2. `public static void main(String args[])`: This is the main method, which serves as the entry point for the Java program.

3. `int num = 100;`: This line declares an integer variable `num` and initializes it with the value 100. Additionally, this variable represents the upper limit of the range for which odd numbers will be printed.

4. `System.out.print(“Odd Numbers from 1 to “+num+” are: “);`: This line prints the introductory message to the console, indicating that the program will print odd numbers from 1 to the specified `num` value.

5. `for (int i = 1; i <= num; i++) {`: This is a for loop that iterates from 1 to the value of `num`.

6. `if (i % 2 != 0) {`: This line checks if the current value of ‘i’ is odd. Additionally, the ‘%’ operator is used to find the remainder after dividing ‘i’ by 2. If the remainder is not equal to 0, it means ‘i’ is an odd number.

7. `System.out.print(i + ” “);`: If `i` is an odd number, it is printed to the console.

8. The for loop continues to iterate until `i` reaches the value of `num`.

Finally, the program outputs all odd numbers from 1 to 100 separated by spaces, following the introductory message printed at the beginning. The output will be something like: “Odd Numbers from 1 to 100 are: 1 3 5 7 … 97 99”.

Output:

Odd Numbers from 1 to 100 are: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99 

Java Program to Print Odd Numbers Using nested-if Statement

// Print Odd Numbers From 1 to 100 in Java
public class DisplayOddnumEx2  
{  
    public static void main(String[] args)   
    {  
        System.out.println("List of odd numbers: ");       
        //method calling  
        displayOddNum(1, 100);   
        }   
        //method that checks the number is odd or not  
        private static void displayOddNum(int number, int end)   
        {   
        if(number>end)   
        return;   
        if(number%2!=0)   
        {   
        //prints the odd numbers  
        System.out.print(number +" ");   
        //calling the method and increments the number by 2 if the number is odd  
        displayOddNum(number + 2, end);   
        }  
        else   
        {   
        //increments the number by 1 if the number is odd  
        displayOddNum(number + 1, end);   
        }   
    }   
}  

Get complete Java Programming Exercises and Solutions here!

Explanation of the code

Java code is another implementation to print odd numbers from 1 to 100 using a recursive method. Let’s understand how this code works:

1. `public class DisplayOddnumEx2`: This line declares a new Java class named `DisplayOddnumEx2`.

2. `public static void main(String[] args)`: This is the main method, the entry point of the Java program.

3. `System.out.println(“List of odd numbers: “);`: This line prints an introductory message to the console, indicating that the program will display a list of odd numbers.

4. `displayOddNum(1, 100);`: This line calls the `displayOddNum` method to start printing odd numbers from 1 to 100. Furthermore, the method will be called with initial parameters ‘number’ as 1 and ‘end’ as 100.

5. `private static void displayOddNum(int number, int end)`: This is a private recursive method that takes two parameters: `number` and `end`. The ‘number’ parameter represents the current number being checked, while the ‘end’ parameter represents the upper limit of the range.

6. `if(number>end) return;`: This is the base case of the recursion. If the current `number` exceeds the `end` value, the method returns, terminating the recursion.

7. `if(number%2!=0)`: This line checks if the `number` is odd by verifying if it leaves a remainder when divided by 2.

8. `System.out.print(number +” “);`: If the ‘number’ is odd, furthermore, it is printed to the console.

9. `displayOddNum(number + 2, end);`: The method calls itself recursively, passing the next odd number (`number + 2`) as the new `number` and the same `end` value. Furthermore, this step ensures that the method continues to check and print odd numbers.

10. `else`: If the `number` is even, this block will be executed.

11. `displayOddNum(number + 1, end);`: The method calls itself recursively, passing the next number (`number + 1`) as the new `number` and the same `end` value. This step ensures that the method skips even numbers and continues checking for the next odd number.

The recursion continues until the base case is reached, ensuring that all odd numbers within the specified range are printed. The output will be something like: “List of odd numbers: 1 3 5 7 … 97 99”.

Output:

List of odd numbers: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99 

Also, learn about Swap of Two Numbers in Java, Now!

Java Program to Print Odd Numbers Using While Loop

// Print Odd Numbers From 1 to 100 in Java
import java.util.Scanner;  
public class DisplayOddNumbersExample3  
{  
    public static void main(String[] args)   
    {  
        int number, i;  
        i=1; 
        number = 100; 
        System.out.print("List of odd numbers: ");  
        //the while loop executes until the condition becomes false  
        while(i<=number)  
        {  
            //prints the odd number  
            System.out.print(i +" ");   
            //increments the variable i by 2  
            i=i+2;  
        }     
    }  
} 

Explanation of the code

Java code is a program to print odd numbers from 1 to 100 using a while loop. The following analysis will shed light on how the code works:

1. `import java.util.Scanner;`: This line imports the Scanner class, which allows us to read input from the user (although it is not used in this code).

2. `public class DisplayOddNumbersExample3`: This line declares a new Java class named `DisplayOddNumbersExample3`.

3. `public static void main(String[] args)`: This is the main method, the entry point of the Java program.

4. `int number, i;`: This line declares two integer variables, `number` and `i`.

5. `i=1;`: This line initializes the variable `i` with the value 1. Moreover, it will be used to keep track of the current number being printed.

6. `number = 100;`: This line initializes the variable `number` with the value 100. It represents the upper limit of the range for which odd numbers will be printed.

7. `System.out.print(“List of odd numbers: “);`: This line prints an introductory message to the console, simultaneously indicating that the program will display a list of odd numbers.

8. `while(i<=number)`: This is a while loop that executes as long as the condition `i <= number` is true.

9. `System.out.print(i +” “);`: This line prints the current value of `i` to the console. Since `i` is initialized to 1 and incremented by 2 in each iteration, it will print all odd numbers from 1 to 100.

10. `i=i+2;`: This line increments the value of `i` by 2 in each iteration. This ensures the printing of only odd numbers since odd numbers are always one less or one more than an even number.

The while loop continues to execute until `i` exceeds the value of `number` (100 in this case). The program outputs all odd numbers from 1 to 100 separated by spaces after the introductory message. Furthermore, The output will be something like: “List of odd numbers: 1 3 5 7 … 97 99”.

Output:

List of odd numbers: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99 

Understand the Concept of Smallest of Three Numbers in Java, Here!

Best Practices

When writing code to print odd numbers from 1 to 100 in Java, adhering to best practices ensures that your code is clean, maintainable, and easy to understand. Here are some essential best practices to follow:

A. Code Readability and Maintainability:

   1. Use Descriptive Variable Names: Choose meaningful names for variables and avoid single-letter names. For example, use `endNumber` instead of `num` to represent the upper limit of the range.

   2. Indentation and Formatting: Properly indent your code and then follow a consistent formatting style to improve readability. Consider using an IDE or code formatted to automate this process.

   3. Avoid Magic Numbers: Instead of hardcoding values like 100 in the code, define constants with meaningful names to improve code clarity and make changes easier.

   4. Modularize the Code: Break down your code into smaller functions or methods to improve code organization and reusability. For example, create separate functions for printing odd numbers, checking oddness, and iterating through the range.

B. Choosing Appropriate Loop Constructs:

   1. Use for Loop for Known Iterations: When you know the exact number of iterations (e.g., printing numbers from 1 to 100), a for loop is a suitable choice, as it clearly defines the loop’s start, end, and increment conditions.

   2. Use while Loop for Unknown Iterations: If the number of iterations is not fixed or depends on certain conditions, a while loop is more appropriate. For instance, when printing odd numbers until a specific condition is met, a while loop is a better fit.

C. Commenting and Documentation:

   1. Add Comments for Complex Logic: If your code includes intricate logic or algorithms, add comments to explain the steps and improve understanding for other developers or your future self.

   2. Document Function Signatures: Clearly describe the purpose, parameters, and return values of your functions using Javadoc or similar documentation styles. Consequently, this helps others quickly grasp the functions’ functionality without diving into the implementation details.

   3. Explain Edge Cases: Comment on how your code handles edge cases like negative inputs, zero, or large ranges. Additionally, this makes the code more robust and helps others understand your thought process.

By following these best practices, you can ensure that your code for printing odd numbers in Java is not only functional but also maintainable and easy to collaborate on with other developers.

In conclusion, learning how to print odd numbers from 1 to 100 in Java is a fundamental skill that enhances coding abilities and problem-solving proficiency. By exploring different approaches, including iterative and functional methods, and adhering to best practices, furthermore, developers can write clean, maintainable code and expand their Java programming expertise.

We hope our blog on “Print odd Numbers from 1 to 100 in Java” was useful and informative. For more coding related blogs and online coding courses visit our website Newtum’s.

About The Author

Leave a Reply