0
0
PythonProgramBeginner · 2 min read

Python Program to Print Zigzag Pattern

You can print a zigzag pattern in Python by using loops and controlling the position of stars with a direction flag; for example, use for loops and a variable to track the current row, moving up and down to create the zigzag shape.
📋

Examples

Inputn = 3, length = 9
Output * * * * * * * * * *
Inputn = 4, length = 12
Output * * * * * * * * * * * * * *
Inputn = 2, length = 5
Output * * * * * * *
🧠

How to Think About It

To print a zigzag pattern, think of placing stars in rows that move down and then up repeatedly. Use a variable to track the current row and a direction flag to know when to go down or up. For each position in the pattern, print a star if it matches the current row, otherwise print a space. Change the row according to the direction to create the zigzag effect.
📐

Algorithm

1
Get the number of rows (n) and the total length of the pattern.
2
Initialize the current row to 0 and direction to down (1).
3
For each position from 0 to length-1:
4
Mark a star at the current row and position.
5
If the current row is the last row, change direction to up (-1).
6
If the current row is the first row, change direction to down (1).
7
Move the current row up or down based on direction.
8
Print the pattern row by row.
💻

Code

python
def print_zigzag(n, length):
    pattern = [[' ' for _ in range(length)] for _ in range(n)]
    row = 0
    direction = 1
    for col in range(length):
        pattern[row][col] = '*'
        if row == n - 1:
            direction = -1
        elif row == 0:
            direction = 1
        row += direction
    for r in pattern:
        print(''.join(r))

print_zigzag(3, 9)
Output
* * * * * * * * * *
🔍

Dry Run

Let's trace the example with n=3 and length=9 through the code

1

Initialize pattern

pattern is a 3x9 grid filled with spaces

2

Start at row=0, direction=1

Place '*' at (0,0)

3

Move down to row=1

Place '*' at (1,1)

4

Move down to row=2

Place '*' at (2,2), change direction to -1

5

Move up to row=1

Place '*' at (1,3)

6

Move up to row=0

Place '*' at (0,4), change direction to 1

7

Move down to row=1

Place '*' at (1,5)

8

Move down to row=2

Place '*' at (2,6), change direction to -1

9

Move up to row=1

Place '*' at (1,7)

10

Move up to row=0

Place '*' at (0,8)

ColumnRowDirectionPattern Position Marked
001(0,0)
111(1,1)
221(2,2)
31-1(1,3)
40-1(0,4)
511(1,5)
621(2,6)
71-1(1,7)
80-1(0,8)
💡

Why This Works

Step 1: Pattern grid creation

We create a 2D list filled with spaces to hold the zigzag pattern, so we can place stars at correct positions.

Step 2: Row and direction control

We use a variable to track the current row and a direction flag to move down or up through rows, creating the zigzag movement.

Step 3: Placing stars

For each column, we place a star at the current row, then update the row based on direction to form the zigzag shape.

Step 4: Printing the pattern

Finally, we print each row as a string, showing the stars and spaces in the zigzag pattern.

🔄

Alternative Approaches

Using string concatenation per row
python
def print_zigzag_alt(n, length):
    row = 0
    direction = 1
    rows = ['' for _ in range(n)]
    for col in range(length):
        for r in range(n):
            if r == row:
                rows[r] += '*'
            else:
                rows[r] += ' '
        if row == n - 1:
            direction = -1
        elif row == 0:
            direction = 1
        row += direction
    for line in rows:
        print(line)

print_zigzag_alt(3, 9)
This method builds each row as a string directly, which can be simpler but less flexible for complex patterns.
Using mathematical formula for star positions
python
def print_zigzag_formula(n, length):
    cycle = 2 * (n - 1)
    for r in range(n):
        line = ''
        for i in range(length):
            if i % cycle == r or i % cycle == cycle - r:
                line += '*'
            else:
                line += ' '
        print(line)

print_zigzag_formula(3, 9)
This approach uses math to find star positions without tracking direction, which is efficient but less intuitive for beginners.

Complexity: O(n * length) time, O(n * length) space

Time Complexity

The program loops through each column and each row to place stars or spaces, resulting in O(n * length) time.

Space Complexity

It uses a 2D list or multiple strings to store the pattern, requiring O(n * length) space.

Which Approach is Fastest?

The formula-based approach is fastest as it avoids extra state tracking, but the loop with direction flag is easier to understand.

ApproachTimeSpaceBest For
Direction flag with 2D listO(n * length)O(n * length)Clear logic and easy to modify
String concatenation per rowO(n * length)O(n * length)Simple code for beginners
Mathematical formulaO(n * length)O(n * length)Efficient and concise for fixed patterns
💡
Use a direction flag to switch between moving down and up rows to create the zigzag effect easily.
⚠️
Beginners often forget to change direction at the first and last rows, causing the pattern to be a straight line.