Java Program to Print Odd Numbers from 1 to N - The Coding Shala

Home >> Java Programs >> Java Program to Print Odd Numbers from 1 to N

 In this post, we will learn How to Display Odd Numbers from 1 to N using Java Program.

Java Program to Print Odd Numbers from 1 to N

Write a Java Program to print odd numbers from 1 to given n. 

Example 1:
Input: 5
Output: 1
             3
             5

Approach:

We can use a for loop from 1 to given n and will check if the current number is divisible by 2 then it is an even number else it is an odd number. We will print all the odd numbers.

We can also start the for loop from 1 and increase it by 2 and print all the numbers till n.

Java Program: 

/**
 * https://www.thecodingshala.com/
 */

import java.util.Scanner;

public class Main {

    public static void printOddNumbers(int n) {
        for(int i = 1; i <= n; i++) {
            // if number is divisible by 2 then its even else odd
            if(i%2 != 0) {
                System.out.println(i);
            }
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter value of n");
        int n = sc.nextInt();
        System.out.println("Odd numbers from 1 to " + n + " are: ");
        printOddNumbers(n);
    }
}

Output: 

Enter value of n
15
Odd numbers from 1 to 15 are: 
1
3
5
7
9
11
13
15


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Anti Diagonals - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

LeetCode - Bulb Switcher Solution - The Coding Shala

New Year Chaos Solution - The Coding Shala

Sorting the Sentence LeetCode Solution - The Coding Shala