Search code examples
c#matrixindexoutofrangeexception

System.Indexoutofrangeexception error not understood


Hi i am a beginner at c# and i did not understand why the exception is thrown at the 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 the degree of matrix:");
            n = int.Parse(Console.ReadLine());
            int[,] num = new int[n, n];
            int p = n * n;
            for (i = 1; i <= p; i++)
            {
                num[x, y] = i;
                if (num[x, y] % n == 0) { y++; }
                if (y % 2 == 0) { x++; }
                if (y % 2 != 0) { x--; }
            }
            for (i = 0; i < n; i++) {
                for (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 an exception as stated in the topic is thrown at num[x ,y]=i; . I do not understand why System.IndexOutOfRangeException occurs as the loop clearly ends at the end of the 2d array.

P.S. the program is meant to run only once.


Solution

  • Maybe I'm wrong, but if you insert 2 as degree of the matrix, the variable p equals 4.

    The external for cycle

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

    cycles 4 times, from 1 to 4. But when i == 4, X equals -1, and you cannot access a matrix with negative index. You get the same behavior with degree = 4, like in your example.