A task: Fill in the sectors of the matrix that lie to the left and right of the main and secondary diagonals, from the upper left corner to the right - down. Fill the rest of the matrix with zeros.
What happened to me:
#include <stdio.h>
int main()
{
int a[9][9], n=9, t=1, i, j;
for(j=0; j<n; j )
for(i=0; i<n; i )
if((j<i && i<n/2) || (j<n-i-1 && i>=n/2) || (j>n-i-1 && i<n/2) || (j>i && i>=n/2))
a[i][j]=t ;
else
a[i][j]=0;
for(i=0; i<n; i )
{
for(j=0; j<n; j )
printf("M", a[i][j]);
printf("\n");
}
return 0;
}
CodePudding user response:
Your first pair of nested nested loops are inverted. The following
for(j=0; j<n; j )
for(i=0; i<n; i )
should be
for(i=0; i<n; i )
for(j=0; j<n; j )
Better code formatting and variable names help to spot errors like these.
Note that introducing a third control variable for the edge distance in each line helps to remove a lot of complexity from the conditional statement.
For example:
#include <stdio.h>
#define SIZE 9
#define GROWTH 1
int main(void)
{
for (int row = 0, edge = 0, number = 1; row < SIZE; row ) {
for (int column = 0; column < SIZE; column ) {
printf("M", (column < edge || SIZE - column <= edge) ? number : 0);
}
printf("\n");
edge = row < SIZE / 2 ? GROWTH : -GROWTH;
}
}
Fixing the for
loop order in your program, or using the example above, both produce this output:
0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 2
3 4 0 0 0 0 0 5 6
7 8 9 0 0 0 10 11 12
13 14 15 16 0 17 18 19 20
21 22 23 0 0 0 24 25 26
27 28 0 0 0 0 0 29 30
31 0 0 0 0 0 0 0 32
0 0 0 0 0 0 0 0 0