Answer the question
In order to leave comments, you need to log in
How to fill in an 8x8 square matrix according to the specified pattern?
Given a one-dimensional array of integers A with dimension 64. Get a square matrix of order 8, the elements of which are the numbers of array A, located in it according to the scheme (I attach the scheme)
My program displays the following:
My code:
int main()
{
int p[64];
int a[8][8];
int n = 8, i = 0, j = 7, k, l = 1;
for (k = 0; k<n*n; k++)
p[k] = k;
for (k = 0; k<n*n; k++)
{
a[i][j] = p[k];
// значение l равно 0 при движении влево по диагонали и 1 при движении вниз
if (i == 0 && j > 0 && l == 0)
{
j--; l = 1;
}
else if (i == n-1 && j > 0 && l == 0)
{
j--; l = 1;
}
else if (i == 0 && j < n - 1 && l == 1)
{
j++; l = 0;
}
else if (j == n - 1 && l == 1)
{
i++; l = 0;
}
else if (l == 0)
{
i--; j++;
}
else
{
i++; j--;
}
}
for (i = 0; i<n; i++)
{
for (j = 0; j<n; j++)
printf("%d ", a[i][j]);
printf("\n");
}
return 0;
}
Answer the question
In order to leave comments, you need to log in
You have i and j changing from 0 to 1 and back and from 7 to 8 and back, respectively. Array elements outside the ranges they specify remain uninitialized, so "garbage" is stored there. As SagePtr pointed out, you should reconsider the conditions under which you move the conditional cursor through the array.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question