Bash Script to Print Multiplication Table
for loops like for i in {1..10}; do for j in {1..10}; do echo "$i x $j = $((i*j))"; done; done to print a multiplication table.Examples
How to Think About It
Algorithm
Code
#!/bin/bash for i in {1..10}; do for j in {1..10}; do echo "$i x $j = $((i * j))" done done
Dry Run
Let's trace printing the multiplication table from 1 to 3.
Outer loop starts with i=1
Inner loop runs j=1 to 3, printing 1 x 1=1, 1 x 2=2, 1 x 3=3
Outer loop i=2
Inner loop runs j=1 to 3, printing 2 x 1=2, 2 x 2=4, 2 x 3=6
Outer loop i=3
Inner loop runs j=1 to 3, printing 3 x 1=3, 3 x 2=6, 3 x 3=9
| i | j | Output |
|---|---|---|
| 1 | 1 | 1 x 1 = 1 |
| 1 | 2 | 1 x 2 = 2 |
| 1 | 3 | 1 x 3 = 3 |
| 2 | 1 | 2 x 1 = 2 |
| 2 | 2 | 2 x 2 = 4 |
| 2 | 3 | 2 x 3 = 6 |
| 3 | 1 | 3 x 1 = 3 |
| 3 | 2 | 3 x 2 = 6 |
| 3 | 3 | 3 x 3 = 9 |
Why This Works
Step 1: Outer loop controls the first number
The for loop with variable i runs through the first number in the multiplication.
Step 2: Inner loop controls the second number
The nested for loop with variable j runs through the second number for each i.
Step 3: Multiplication and printing
Inside the inner loop, $((i * j)) calculates the product, and echo prints the formatted result.
Alternative Approaches
#!/bin/bash i=1 while [ $i -le 10 ]; do j=1 while [ $j -le 10 ]; do echo "$i x $j = $((i * j))" ((j++)) done ((i++)) done
#!/bin/bash for i in {1..10}; do for j in {1..10}; do printf "%d\t" $((i * j)) done echo done
#!/bin/bash for i in $(seq 1 10); do for j in $(seq 1 10); do echo "$i x $j = $((i * j))" done done
Complexity: O(n^2) time, O(1) space
Time Complexity
The script uses two nested loops each running n times, so it performs n × n = n² multiplications and prints.
Space Complexity
The script uses a fixed amount of memory for variables and output lines, so space is constant O(1).
Which Approach is Fastest?
Using for loops with brace expansion is fastest and simplest; while loops and seq add slight overhead but offer flexibility.
| Approach | Time | Space | Best For |
|---|---|---|---|
| For loops with brace expansion | O(n^2) | O(1) | Simple and fast on modern Bash |
| While loops | O(n^2) | O(1) | More control, slightly longer code |
| Seq command | O(n^2) | O(1) | Compatibility on systems without brace expansion |