c# - System.Indexoutofrangeexception error not understood -


hi beginner @ c# , did not understand why exception thrown @ program shown below

program:

using system; using system.collections.generic; using system.linq; using system.text; using system.threading.tasks;  namespace consoleapplication2 {     class program     {         static void main(string[] args)         {             int n, i, x=0, y=0;             console.writeline("enter degree of matrix:");             n = int.parse(console.readline());             int[,] num = new int[n, n];             int p = n * n;             (i = 1; <= p; i++)             {                 num[x, y] = i;                 if (num[x, y] % n == 0) { y++; }                 if (y % 2 == 0) { x++; }                 if (y % 2 != 0) { x--; }             }             (i = 0; < n; i++) {                 (int j = 0; j < n; j++) {                     console.write(num[i, j] + " ");                 }                 console.writeline();             }             console.readline();         }     } } 

required result:

enter order of matrix: 4  1 8 9  16 2 7 10 15 3 6 11 14  4 5 12 13 

but exception stated in topic thrown @ num[x ,y]=i; . not understand why system.indexoutofrangeexception occurs loop ends @ end of 2d array.

p.s. program meant run once.

maybe i'm wrong, if insert 2 degree of matrix, variable p equals 4.

the external cycle

for (i = 1; <= p; i++) 

cycles 4 times, 1 4. when == 4, x equals -1, , cannot access matrix negative index. same behavior degree = 4, in example.


Comments