Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to print the following series. 1 3 5 7... n

Java Code Example — Series Programs

ADVERTISEMENT

Java Program to print the following series. 1 3 5 7... n

Objective

Write a Java program to print the odd number series 1, 3, 5, 7 ... N.

Algorithm / Approach

  1. Ask the user for the upper bound N.
  2. Read n using the Scanner class.
  3. Start a for loop with i initialized to 1 (the first positive odd number).
  4. Check the condition i ≤ n.
  5. Print i, then increment it by 2 on each iteration (i = i + 2).
Test.java
import java.util.Scanner;
class Test {
 public static void main(String[] a)
 {
  Scanner s=new Scanner(System.in);
  System.out.print("Enter N: ");
  int n = s.nextInt();
  for(int i = 1; i<=n; i=i+2) {
   System.out.print(i+"  ");
  } 
 }
}

Expected Output

Enter N: 16
1  3  5  7  9  11  13  15

Explanation of the Program

  • This follows the exact same logic as the even number series, but shifts the starting point.
  • Because we start at 1 (an odd number) and add 2 on each step, every subsequent number generated will also be mathematically odd.
  • This avoids the need for an expensive modulo operation inside the loop.

Complexity

Time Complexity O(n)
Space Complexity O(1)
ADVERTISEMENT