title: C# - Create a 2D Array and then loop through it
body: <p>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.</p>
  
  <p>So for example, if I printed the box/rectangle out it would look something like this:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>Basically, I can't figure out how to create the array with a different number of rows and columns and then loop through it. </p>
  
  <p>Any clues would be appreciated, thanks.</p>
  
  <p>My code:</p>
  
  <pre><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 &lt; column; i++)
              {
                  for (int j = 0; j &lt; row; j++)
                  {
                      array[i, j] = rand.Next(0, 10);
  
                  }
              }
  
  
              for (int i = 0; i &lt; array.GetLength(0); i++)
              {
                  for (int j = 0; j &lt; array.GetLength(1); j++)
                  {
                      Console.Write(array[i, j].ToString() + " ");
                  }
                  Console.WriteLine("");
              }
          }
      }
  }
  </code></pre>