0
0
Bash-scriptingHow-ToBeginner · 2 min read

Bash Script to Print Even Numbers from 1 to n

Use a Bash loop with for i in $(seq 2 2 $n) and print each i to output even numbers from 1 to n.
📋

Examples

Input5
Output2 4
Input10
Output2 4 6 8 10
Input1
Output
🧠

How to Think About It

To print even numbers from 1 to n, start counting from 2 (the first even number) and increase by 2 each time until you reach or pass n. This way, you only check even numbers without extra conditions.
📐

Algorithm

1
Get input number n from the user.
2
Start a loop from 2 to n, increasing by 2 each time.
3
Print the current number in each loop iteration.
4
Stop when the current number exceeds n.
💻

Code

bash
#!/bin/bash
read -p "Enter a number n: " n
for ((i=2; i<=n; i+=2))
do
  echo "$i"
done
Output
2 4 6 8 10
🔍

Dry Run

Let's trace input n=5 through the code

1

Input

User enters n=5

2

Loop start

i=2, check if 2 <= 5 (true)

3

Print

Print 2

4

Increment

i=4, check if 4 <= 5 (true)

5

Print

Print 4

6

Increment

i=6, check if 6 <= 5 (false), stop loop

i
2
4
💡

Why This Works

Step 1: Start from 2

We start the loop at 2 because it is the smallest even number greater than 1.

Step 2: Increment by 2

Increasing by 2 each time ensures only even numbers are considered.

Step 3: Loop until n

The loop stops when the current number exceeds n, so we only print even numbers up to n.

🔄

Alternative Approaches

Using seq command
bash
#!/bin/bash
read -p "Enter a number n: " n
for i in $(seq 2 2 $n); do
  echo "$i"
done
This uses the seq command to generate even numbers; it is simple but depends on seq availability.
Using if condition inside loop
bash
#!/bin/bash
read -p "Enter a number n: " n
for ((i=1; i<=n; i++)); do
  if (( i % 2 == 0 )); then
    echo "$i"
  fi
done
This checks each number if it is even, which is less efficient but easy to understand.

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, only storing loop variables, so space complexity is O(1).

Which Approach is Fastest?

Using a loop that increments by 2 is faster than checking each number with a condition, as it skips odd numbers entirely.

ApproachTimeSpaceBest For
Increment by 2 loopO(n)O(1)Efficient and simple
seq commandO(n)O(1)Simple but depends on external command
Check each number with ifO(n)O(1)Easy to understand but less efficient
💡
Use for ((i=2; i<=n; i+=2)) to loop only over even numbers efficiently.
⚠️
Beginners often start from 1 and check evenness inside the loop, which is less efficient.