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

1 Answer

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
...