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.
from Recent Questions - Stack Overflow http://ift.tt/29Q2qeN
via https://ifttt.com/ IFTTT
No comments:
Post a Comment