I
I
ilya7777412018-06-30 19:56:38
C++ / C#
ilya777741, 2018-06-30 19:56:38

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)
5b37b55e9d2ad169580826.png
My program displays the following:
5b37b5af3191c079644897.png
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;
}

Help me figure out what I did wrong? Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wundarshular, 2018-07-01
@Wundarshular

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 question

Ask a Question

731 491 924 answers to any question