I'm trying to write code that will: Create a multidimensional array, and then loop through all the rows and columns and place a random number between 0 to 9 in that cell.
So for example, if I printed the box/rectangle out it would look something like this:
1 4 6 2 4 1
4 5 6 9 2 1
0 2 3 4 5 9
2 5 6 1 9 4
3 6 7 2 4 6
7 2 2 4 1 4
The code I have (I believe) works OK, however, it only works if I create the array with an equal number of rows and columns (eg, 10x10, 20x20, 15x15) but if I try something like 30x10 I get:
Unhandled Exception: System.IndexOutOfRangeException: Index was outside the boun
ds of the array.
at ConsoleApplication2.Program.Main(String[] args) in c:\Users\Lloyd\Document
s\Visual Studio 2010\Projects\ConsoleApplication2\ConsoleApplication2\Program.cs
:line 22
Basically, I can't figure out how to create the array with a different number of rows and columns and then loop through it.
Any clues would be appreciated, thanks.
My code:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
//The width and height of the box.
const int row = 30;
const int column = 10;
static void Main(string[] args)
{
int[,] array = new int[row, column];
Random rand = new Random();
for (int i = 0; i < column; i++)
{
for (int j = 0; j < row; j++)
{
array[i, j] = rand.Next(0, 10);
}
}
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(1); j++)
{
Console.Write(array[i, j].ToString() + " ");
}
Console.WriteLine("");
}
}
}
}