You code has several mistakes:
The biggest problem is that your not initializing your loop counters where you should:
for(i; i < size; i++){
for(j; j < size; j++){
With that, i
& j
are left as they were prior to the for
statement. The first section of these statements does nothing at all. While that's harmless for i
(since it's initialized to 0 before the for
), that's devastating for j
, which never goes back to 0. Your code should be:
for(i = 0; i < size; i++){
for(j = 0; j < size; j++){
The same issue exists with k
& l
, and the same fix should be applied:
for(k = 0; k < size; k++){
for(l = 0; l < size; l++){
Next, you're "rotating" access in your array. When you fill the array with values, you have i
in your outer loop and j
in the inner loop, and you use them as [i][j]
:
array[i][j] = '1';
Think of that as Out
& In
--> [Out][In]
.
When you print the array, you "rotate" that, k
is outer & l
is inner, and you use them as [l][k]
:
printf("%c", array[l][k]);
That's like doing [In][Out]
.
While that's not a problem with all values being identical ('1'
), and the matrix being square (width == height), it won't work with other values or dimensions, and is confusing.
Last, you're attempt to print a new line is wrong. You have a %
specifier, but your not really using any valid character after that, and you don't need that anyway, just print:
printf("\n");
So, all together, here's what the code should be:
run(int x)
{
int size = 2*x -1;
char array[size][size];
int i,j;
for(i = 0; i < size; i++){
for(j = 0; j < size; j++){
array[i][j] = '1';
}
}
int k, l;
for(k = 0; k < size; k++){
for(l = 0; l < size; l++){
printf("%c", array[k][l]);
}
printf("\n");
}
}
(And as a side note, k
& l
are not really required, you can simply reuse i
& j
)