Home » Java » Get odd numbers in a given range – java

Get odd numbers in a given range – java

In this tutorial, you will learn how to find all the odd numbers between a given range using java.

In this case, I created a class call OddNumbers and a static method call getOdd. We can call static methods directly without creating objects in java. Also, because of clarity, here I created that as a help-method.

I declared two variables “left” and “right” by assigning 3 and 9. Those are the given boundaries. In the other hands, we have to find all the odd numbers within 3 and 9.

Here, the for loop runs from left boundary to right boundary. Inside that for loop, there is a condition to check odd numbers. In programming, % is an operator call modules operator. It will give remainder after division of one number by another.

So, to get odd numbers, the remainder of the division of each number within the given rage should be equal to zero. That is the logic we use here in line 1.

After capturing each odd number it will print.

public class OddNumbers {

    public static void main(String[] args) {
        
        getOdd();
        
    }

    static void getOdd() {
        int left = 3;
        int right = 9;
                
        for (int i = left; i < right + 1; i++) {
           if (i % 2 == 1){
               System.out.println(i);
           }
        }
    }
}
Please follow us:
error

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*

FACEBOOK
FACEBOOK
YOUTUBE
YOUTUBE