How to create zig zag pattern (2d rows and columns) with numbers in C

2 Answers

0 votes
#include <stdio.h>
#include <stdlib.h>
  
int main() {
    int row_cols = 5;
  
    int *arr = malloc(sizeof(int) * row_cols * row_cols);
     
    for (int i, val = 0; i < row_cols * 2; i++)
        for (int j = (i < row_cols) ? 0 : i - row_cols + 1; j <= i && j < row_cols; j++)
            arr[(i & 1) ? j * (row_cols - 1) + i : (i - j) * row_cols + j] = val++;
  
    for (int i = 0; i < row_cols * row_cols; putchar((++i % row_cols) ? ' ' : '\n'))
        printf("%3d", arr[i]);
 
    free(arr);
     
    return 0;
}
 
 
 
 
/*
run:
 
  0   1   5   6  14
  2   4   7  13  15
  3   8  12  16  21
  9  11  17  20  22
 10  18  19  23  24
 
*/

 



answered Mar 13, 2022 by avibootz
edited Mar 14, 2022 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>

/*
    FUNCTION: fill_diagonal_pattern
    --------------------------------
    This function fills a 1D array (representing a 2D square)
    using the same diagonal‑based logic from the original code.

    Explanation of the pattern:
    - The square is filled along diagonals.
    - i goes from 0 to row_cols*2 - 1, representing each diagonal.
    - j iterates across each diagonal.
    - The index formula chooses whether the diagonal is going
      left→right or top→bottom based on (i & 1).

    This function produces the same output as the original code.
*/
void fill_diagonal_pattern(int *arr, int row_cols) {
    int val = 0;

    for (int i = 0; i < row_cols * 2; i++) {

        // j start depends on whether diagonal is in upper or lower half
        int j_start = (i < row_cols) ? 0 : i - row_cols + 1;

        for (int j = j_start; j <= i && j < row_cols; j++) {

            /*
                Indexing logic:
                - If i is odd → fill using j * (row_cols - 1) + i
                - If i is even → fill using (i - j) * row_cols + j

                This zig‑zag pattern creates the diagonal fill.
            */
            int index = (i & 1)
                        ? j * (row_cols - 1) + i
                        : (i - j) * row_cols + j;

            arr[index] = val++;
        }
    }
}

/*
    FUNCTION: print_square
    -----------------------
    Prints the 1D array as a 2D square.
*/
void print_square(int *arr, int row_cols) {
    for (int i = 0; i < row_cols * row_cols; i++) {
        printf("%3d", arr[i]);
        putchar((i + 1) % row_cols ? ' ' : '\n');
    }
}

int main() {
    int row_cols = 5;

    // Allocate memory for n×n square
    int *arr = malloc(sizeof(int) * row_cols * row_cols);

    fill_diagonal_pattern(arr, row_cols);

    print_square(arr, row_cols);

    free(arr);
    
    return 0;
}


/*
run:

  0   1   5   6  14
  2   4   7  13  15
  3   8  12  16  21
  9  11  17  20  22
 10  18  19  23  24

*/

 



answered Jun 20 by avibootz

Related questions

...