Piotr - 1 year ago 87
C Question

# Zigzag array in ANSI C

I'm just a beginner and I'm trying to figure out how to create two-dimensional array, filled with numbers diagonally like in JPEG zigzag ordering: https://en.wikipedia.org/wiki/File:JPEG_ZigZag.svg

I figured out how to get the upper-left part:

``````r=1;
for(z=0;z<n;z++)
{
if(z%2=0)
{
for(i=0;i<=z;i++)
{
t[z-i][i]=r;
++r;
}
}
else
{
for(i=0;i<=z;i++)
{
t[i][z-i]=r;
++r;
}
}
}
``````

And it works fine, but I can't figure out how to get the rest of it.

I saw that, but C code shown there is too advanced for me

You could just keep doing what you're doing with another nested set of `for` loops and revised indexes:

``````#include <stdio.h>

#define SIZE 8

void zigZagArray(int *array, int n) {
int r = 1;

for (int z = 0; z < n; z++) {
if (z % 2 == 0) {
for (int i = 0; i <= z; i++) {
// array[z - i][i] = r++;
*((array + (z - i) * n) + i) = r++;
}
} else {
for (int i = 0; i <= z; i++) {
// array[i][z - i] = r++;
*((array + i * n) + z - i) = r++;
}
}
}

for (int z = 1; z < n; z++) {
if (z % 2 == 0) {
for (int i = 1; i <= n - z; i++) {
// array[z + i - 1][n - i] = r++;
*((array + (z + i - 1) * n) + n - i) = r++;
}
} else {
for (int i = 1; i <= n - z; i++) {
// array[n - i][z + i - 1] = r++;
*((array + (n - i) * n) + z + i - 1) = r++;
}
}
}
}

void printArray(int *array, int n)
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%2d ", *((array + i * n) + j));
}
printf("\n");
}
}

int main() {

int array[SIZE][SIZE];

zigZagArray((int *) array, SIZE);

printArray((int *) array, SIZE);

return 0;
}
``````

Not pretty, but it works:

``````> ./a.out
1  2  6  7 15 16 28 29
3  5  8 14 17 27 30 43
4  9 13 18 26 31 42 44
10 12 19 25 32 41 45 54
11 20 24 33 40 46 53 55
21 23 34 39 47 52 56 61
22 35 38 48 51 57 60 62
36 37 49 50 58 59 63 64
>
``````

Actually, it doesn't work. Changing the size, sometimes it's right, sometimes it isn't. (E.g. try `define SIZE 7`.) You can try to sort it out or wait for a better answer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download