Home > database >  how to create a matrix with 1 for loop c#
how to create a matrix with 1 for loop c#

Time:12-27

How can i make a matrix as the one seen below, but with simply 1 for loop (instead of two):

 1  2  3  4  5  6  7  8

 9 10 11 12 13 14 15 16

17 18 19 20 21 22 23 24

25 26 27 28 29 30 31 32

33 34 35 36 37 38 39 40

41 42 43 44 45 46 47 48

49 50 51 52 53 54 55 56

57 58 59 60 61 62 63 64

Ive made the one above using 2 nested for loops, the first to create the rows and the second for the columns. How can i achieve the same result but with one for loop? Preferably implementing the / and % operators.

CodePudding user response:

It is enough to have a loop from 1 to 63. Divide by 8 for the row and calculate the remainder by 8 for the column (plus one is because the loop starts from zero):

        int[,] matrix= new int[8,8];
        for (int i = 0; i <= 63; i  )
                matrix[i/8,i%8] = i 1;
  • Related