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
- Ask the user for the upper bound
N. - Read
nusing the Scanner class. - Start a
forloop withiinitialized to 1 (the first positive odd number). - Check the condition
i ≤ n. - 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)