Print Zig-Zag Pattern

Print Zig-Zag Pattern

Hard C++ Pattern Printing 31 views
Explanation Complexity

Problem Statement

Print numbers in zig-zag diagonal pattern.
Real Life: Understanding diagonal pattern logic.

Input Format

An integer n (size of square matrix).

Output Format

Numbers printed in zig-zag diagonal pattern.

Example

4
1
2 5
6 3
4 7 10
11 8
9 12
13
14 15
16
(numbers filled row-wise, then printed diagonally in zig-zag)

Constraints

• n ≥ 1

• Use loops only

• Matrix size is n × n

Concept Explanation

Zig-zag diagonal means:

• We move diagonal by diagonal

• One diagonal is printed top-down

• Next diagonal is printed bottom-up

• Direction keeps alternating

This helps understand row-column relationship and diagonal traversal.

Step-by-Step Explanation

1.Create an n × n matrix.

2.Fill matrix with numbers from 1 to n*n row-wise.

3.Total diagonals = 2*n - 1.

4.For each diagonal index d from 0 to 2*n-2:

• If d is even → print diagonal top to bottom

• If d is odd → print diagonal bottom to top

5.Row and column relation:

• row + col = d

6.Print valid (row, col) pairs only (inside matrix).

Concept Explanation

Zig-zag diagonal means:

• We move diagonal by diagonal

• One diagonal is printed top-down

• Next diagonal is printed bottom-up

• Direction keeps alternating

This helps understand row-column relationship and diagonal traversal.

Step-by-Step Explanation

1.Create an n × n matrix.

2.Fill matrix with numbers from 1 to n*n row-wise.

3.Total diagonals = 2*n - 1.

4.For each diagonal index d from 0 to 2*n-2:

• If d is even → print diagonal top to bottom

• If d is odd → print diagonal bottom to top

5.Row and column relation:

• row + col = d

6.Print valid (row, col) pairs only (inside matrix).

Input / Output Format

Input Format
An integer n (size of square matrix).
Output Format
Numbers printed in zig-zag diagonal pattern.
Constraints
• n ≥ 1

• Use loops only

• Matrix size is n × n

Examples

Input:
4
Output:
1 2 5 6 3 4 7 10 11 8 9 12 13 14 15 16 (numbers filled row-wise, then printed diagonally in zig-zag)

Example Solution (Public)

C++
void pattern_q13_zigzag() {
    int rows = 3;
    int cols = 20;
    
    for(int i = 1; i <= rows; i++) {
        for(int j = 1; j <= cols; j++) {
            if((i + j) % 4 == 0 || (i == 2 && j % 4 == 0)) {
                cout << "*";
            } else {
                cout << " ";
            }
        }
        cout << endl;
    }
}

Official Solution Code

void pattern_q13_zigzag() {
    int rows = 3;
    int cols = 20;
    
    for(int i = 1; i <= rows; i++) {
        for(int j = 1; j <= cols; j++) {
            if((i + j) % 4 == 0 || (i == 2 && j % 4 == 0)) {
                cout << "*";
            } else {
                cout << " ";
            }
        }
        cout << endl;
    }
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.