Bash Script to Print Alphabet Pattern with Loop
Use a Bash script with a loop and
printf to print letters from A to Z in a pattern, for example: for i in {A..Z}; do printf "%s " "$i"; done; echo.Examples
InputPrint letters A to E
OutputA B C D E
InputPrint letters A to Z
OutputA B C D E F G H I J K L M N O P Q R S T U V W X Y Z
InputPrint letters A to C
OutputA B C
How to Think About It
To print an alphabet pattern in Bash, think of the alphabet as a sequence of letters from A to Z. Use a loop to go through each letter and print it. You can control how many letters to print by setting the loop range. Use
printf to print letters on the same line with spaces.Algorithm
1
Decide the range of letters to print (e.g., A to E).2
Start a loop from the first letter to the last letter.3
In each loop iteration, print the current letter followed by a space.4
After the loop ends, print a newline to finish the pattern.Code
bash
for letter in {A..E}; do printf "%s " "$letter" done printf "\n"
Output
A B C D E
Dry Run
Let's trace printing letters A to E through the code
1
Start loop
letter = A
2
Print letter
Output: 'A '
3
Next letter
letter = B, Output: 'A B '
| Iteration | Letter | Output So Far |
|---|---|---|
| 1 | A | A |
| 2 | B | A B |
| 3 | C | A B C |
| 4 | D | A B C D |
| 5 | E | A B C D E |
Why This Works
Step 1: Loop over letters
The for loop iterates over letters from A to E using brace expansion.
Step 2: Print each letter
Inside the loop, printf "%s " prints the current letter followed by a space without a newline.
Step 3: Print newline
After the loop, printf "\n" prints a newline to move to the next line.
Alternative Approaches
Using ASCII codes with printf
bash
for ((i=65; i<=69; i++)); do printf "%c " "$i" done printf "\n"
Uses ASCII decimal codes for letters; more flexible for custom ranges but less readable.
Using seq and awk
bash
seq 65 69 | awk '{printf "%c ", $1} END {print ""}'
Uses external tools to print letters; useful if you want to combine with other commands.
Complexity: O(n) time, O(1) space
Time Complexity
The loop runs once per letter, so time grows linearly with the number of letters printed.
Space Complexity
The script uses constant extra space, only storing the current letter in the loop.
Which Approach is Fastest?
Using brace expansion is fastest and simplest in Bash; ASCII code loops add complexity but allow more control.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Brace Expansion | O(n) | O(1) | Simple alphabet loops |
| ASCII Codes with printf | O(n) | O(1) | Custom letter ranges |
| seq and awk | O(n) | O(1) | Combining with other commands |
Use brace expansion like {A..Z} in Bash to easily loop over alphabets.
Forgetting to print a newline after the loop causes the prompt to stay on the same line.