Python Program to Print Multiplication Table Pattern
for loops in Python to print a multiplication table pattern, for example: for i in range(1, n+1): for j in range(1, n+1): print(i*j, end='\t') print().Examples
How to Think About It
Algorithm
Code
n = int(input('Enter the size of multiplication table: ')) for i in range(1, n + 1): for j in range(1, n + 1): print(i * j, end='\t') print()
Dry Run
Let's trace the program with n = 3 to see how it prints the multiplication table.
Input
User inputs n = 3
Outer loop i=1
Inner loop runs j=1 to 3, prints 1*1=1, 1*2=2, 1*3=3
Outer loop i=2
Inner loop runs j=1 to 3, prints 2*1=2, 2*2=4, 2*3=6
Outer loop i=3
Inner loop runs j=1 to 3, prints 3*1=3, 3*2=6, 3*3=9
| i | j | i*j |
|---|---|---|
| 1 | 1 | 1 |
| 1 | 2 | 2 |
| 1 | 3 | 3 |
| 2 | 1 | 2 |
| 2 | 2 | 4 |
| 2 | 3 | 6 |
| 3 | 1 | 3 |
| 3 | 2 | 6 |
| 3 | 3 | 9 |
Why This Works
Step 1: Outer loop controls rows
The outer for loop runs from 1 to n, each iteration representing a row in the table.
Step 2: Inner loop controls columns
The inner for loop runs from 1 to n, each iteration representing a column in the current row.
Step 3: Print product with tab
Inside the inner loop, multiply the row and column numbers and print the result with a tab to align columns.
Step 4: New line after each row
After finishing each row, print a newline to start the next row on a new line.
Alternative Approaches
n = int(input('Enter size: ')) for i in range(1, n+1): print('\t'.join(str(i*j) for j in range(1, n+1)))
n = int(input('Enter size: ')) i = 1 while i <= n: j = 1 while j <= n: print(i*j, end='\t') j += 1 print() i += 1
Complexity: O(n^2) time, O(1) space
Time Complexity
The program uses two nested loops each running n times, so it performs n*n = n^2 multiplications and prints.
Space Complexity
The program uses constant extra space, only variables for loop counters and no additional data structures.
Which Approach is Fastest?
All approaches have the same time complexity O(n^2). Using list comprehension may be slightly slower due to string joining overhead but is more concise.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Nested for loops | O(n^2) | O(1) | Clarity and simplicity |
| List comprehension with join | O(n^2) | O(1) | Concise code |
| While loops | O(n^2) | O(1) | Explicit loop control |
\t to align columns neatly in the multiplication table output.