Python Program to Print Odd Numbers from 1 to n
Use a
for loop with a step of 2 starting from 1 up to n like for i in range(1, n+1, 2): print(i) to print odd numbers from 1 to n.Examples
Input5
Output1
3
5
Input10
Output1
3
5
7
9
Input1
Output1
How to Think About It
To print odd numbers from 1 to n, start counting from 1 and move forward by adding 2 each time. This way, you only get odd numbers. Stop when you reach or pass n.
Algorithm
1
Get the input number n.2
Start a loop from 1 to n, increasing by 2 each time.3
Print the current number in the loop.4
Stop when the current number is greater than n.Code
python
n = int(input("Enter the value of n: ")) for i in range(1, n + 1, 2): print(i)
Output
Enter the value of n: 10
1
3
5
7
9
Dry Run
Let's trace the program with input n = 5 to see how it prints odd numbers.
1
Input
User enters n = 5
2
Loop start
Start loop with i = 1
3
Print i
Print 1
4
Next i
Increase i by 2, i = 3
5
Print i
Print 3
6
Next i
Increase i by 2, i = 5
7
Print i
Print 5
8
Next i
Increase i by 2, i = 7 (greater than n, stop loop)
| i |
|---|
| 1 |
| 3 |
| 5 |
Why This Works
Step 1: Start from 1
We start counting from 1 because it is the first odd number.
Step 2: Increment by 2
Adding 2 each time ensures we only get odd numbers (1, 3, 5, ...).
Step 3: Stop at n
We stop the loop when the number exceeds n to avoid printing numbers beyond the limit.
Alternative Approaches
Using if condition inside a loop
python
n = int(input("Enter the value of n: ")) for i in range(1, n + 1): if i % 2 != 0: print(i)
This checks every number from 1 to n and prints it only if it is odd; less efficient but easy to understand.
Using list comprehension and join
python
n = int(input("Enter the value of n: ")) print('\n'.join(str(i) for i in range(1, n + 1) if i % 2 != 0))
Creates a list of odd numbers and prints them all at once; concise but uses more memory.
Complexity: O(n) time, O(1) space
Time Complexity
The loop runs roughly n/2 times because it skips even numbers, so time complexity is O(n).
Space Complexity
The program uses constant extra space, O(1), as it prints numbers directly without storing them.
Which Approach is Fastest?
Using range(1, n+1, 2) is faster than checking each number with if because it skips even numbers entirely.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Range with step 2 | O(n) | O(1) | Efficient and simple for printing odd numbers |
| If condition inside loop | O(n) | O(1) | Easy to understand but less efficient |
| List comprehension | O(n) | O(n) | Concise but uses extra memory for list |
Use
range(1, n+1, 2) to efficiently loop through odd numbers only.Beginners often forget to add 1 to n in
range, missing the last odd number if n is odd.