Reputation: 11
public static void Main(string[] args)
{
int width;
int height;
Console.WriteLine("Please enter the width of the array");
width = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the height of the array");
height = Convert.ToInt32(Console.ReadLine());
int[,] grid = new int [width,height];
for(int x = 0; x < width; x++)
{
for(int y = 0; y < height; y++)
{
Console.WriteLine(grid[x][y]);
}
}
Just to be clear i am a beginner, and all the other answers are either way too complex or i just straight up cant understand them. the line in which i am getting the error is this:
int[,] grid = new int[width, height];
Upvotes: 0
Views: 1869
Reputation: 105
Use Console.WriteLine(grid[x, y]);
instead of Console.WriteLine(grid[x][y]);
Upvotes: 1
Reputation: 239824
You're mixing up multidimensional arrays and jagged arrays. Multidimensional arrays are always rectangular1, and are indexed by multiple indices inside a single indexer:
grid[x,y]
Jagged arrays are arrays of arrays, and are not necessarily rectangular. You access an element by indexing into the outer array with one indexer, and then using a second indexer to access the element:
grid[x][y]
In your case, you've created a multidimensional array - you need to use the first syntax.
1Or whatever the appropriate term is with a higher number of dimensions.
Upvotes: 7