0
0
Bash-scriptingHow-ToBeginner · 2 min read

Bash Script to Print Odd Numbers from 1 to n

Use a Bash for loop with a step of 2 starting at 1: for ((i=1; i<=n; i+=2)); do echo $i; done to print odd numbers from 1 to n.
📋

Examples

Input1
Output1
Input7
Output1 3 5 7
Input0
Output
🧠

How to Think About It

To print odd numbers from 1 to n, start counting from 1 and increase by 2 each time. This way, you only hit odd numbers. Stop when you reach or pass n.
📐

Algorithm

1
Get the input number n.
2
Start a counter at 1.
3
While the counter is less than or equal to n, do:
4
Print the counter.
5
Increase the counter by 2.
6
Stop when the counter is greater than n.
💻

Code

bash
#!/bin/bash
read -p "Enter a number n: " n
for ((i=1; i<=n; i+=2)); do
  echo $i
done
Output
Enter a number n: 7 1 3 5 7
🔍

Dry Run

Let's trace input n=7 through the code

1

Initialize i

i=1, n=7

2

Check condition i <= n

1 <= 7 is true, print 1

3

Increment i by 2

i=3

4

Repeat check and print

3 <= 7 true, print 3; i=5

5

Repeat check and print

5 <= 7 true, print 5; i=7

6

Repeat check and print

7 <= 7 true, print 7; i=9

7

Check condition fails

9 <= 7 false, stop

i
1
3
5
7
💡

Why This Works

Step 1: Start at 1

We begin counting from 1 because it is the first odd number.

Step 2: Increment by 2

Adding 2 each time skips even numbers, so only odd numbers are printed.

Step 3: Stop at n

The loop stops when the number exceeds n to avoid printing numbers beyond the limit.

🔄

Alternative Approaches

Using modulo check inside a loop
bash
#!/bin/bash
read -p "Enter a number n: " n
for ((i=1; i<=n; i++)); do
  if (( i % 2 == 1 )); then
    echo $i
  fi
done
This checks every number but prints only odd ones; less efficient but easy to understand.
Using seq command with step
bash
read -p "Enter a number n: " n
seq 1 2 $n
Uses built-in seq command to generate odd numbers; very concise but depends on seq availability.

Complexity: O(n/2) time, O(1) space

Time Complexity

The loop runs roughly n/2 times because it increments by 2, so time complexity is O(n/2), which simplifies to O(n).

Space Complexity

The script uses constant extra space for variables, so space complexity is O(1).

Which Approach is Fastest?

The direct increment by 2 approach is fastest because it skips even numbers, unlike the modulo check method which tests every number.

ApproachTimeSpaceBest For
Increment by 2 loopO(n)O(1)Efficient and simple
Modulo check loopO(n)O(1)Easy to understand, less efficient
seq commandO(n)O(1)Concise, depends on external command
💡
Use i+=2 in the loop to jump directly to odd numbers without extra checks.
⚠️
Beginners often forget to increment by 2 and print all numbers instead of only odd ones.