C# Intermediate

Rectangular Array

The objective of this article is to familiarize you with the rectangular array, also referred to as matrices. Arrays can be of different dimensions, one or two, but the most commonly used 2D array is the rectangular array. You will learn how to declare, create, instantiate and use this type of array. Finally, different ways to iterate through all the elements of the array.

There are two kinds of multi-dimensional arrays: Rectangular and Jagged.
A rectangular array is an array of two (or more) dimensions separated by comma. You can think of a rectangular array as a table, where the first dimension is the number of rows and the second dimension is the number of columns keeping in mind that every row is the same length. Due to 2 dimensions, it’s also known as two-dimensional array or 2D array.

Array Declaration and Instantiation Using Two Statements

On the left side of the declaration, you need to have a comma within the set of brackets that follows the data type declaration. Comma (,) indicates that the array has two dimensions. Two or more commas would indicate three or more dimensions.

Syntax

type[,] arrayName;

Example

int[,] intArray;

On the right side of instantiation, new keyword is used to create an array. You specify the number of rows in the array, followed by a comma, followed by the number of columns to set the size of each dimension in the array.

Syntax

arrayName = new type[rows, columns]; // 2D array
  • type[,] indicates 2D array
  • type[rows, columns] indicates size of row and column

Example

intArray = new int[3, 2];


Note: Multi-dimensional array is indexed by two or more integers.

Array Declaration and Instantiation Combined on a Single Line

Declaration and initialization of an array at the same time on a single line.

Syntax

type[,] arrayName = new type[rows, columns];

Example

int[,] intArray = new int[3, 2];

Create and Assign Values to an Array

Array elements can be referenced using two integers with an indexer, one statement at a time to assign values to the elements of the intArray as shown below.

int[,] intArray = new int[3, 2];

intArray[0, 0] = 1;
intArray[0, 1] = 2;
intArray[1, 0] = 3;
intArray[1, 1] = 4;
intArray[2, 0] = 5;
intArray[2, 1] = 6;

You can use second method, which is quite convenient. With this method, values can be assigned all at once using a curly bracket {…} notation.

int[,] intArray = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } };

If you initialize the array using curly-bracket syntax, then you can omit the dimensions of the array. The C# compiler determines the size from the number of elements assigned to it.

int[,] intArray = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } };

There’s a shorter form below.

int[,] intArray = { { 1, 2 }, { 3, 4 }, { 5, 6 } };

Another way with var keyword

var intArray = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } };

Run Demo

Access Individual Array Elements

You refer array element using its row and column index because each element of multi-dimensional array is identified with an index for each dimension.

Syntax

arrayName[rowIndex, columnIndex]

Each array element can be accessed by using two integers with an indexer.

Example

Console.WriteLine(intArray[1, 1]); // 0

Run Demo

Example 1: Rectangular 3 by 2 Array

To declare rectangular array, use comma to separate each dimension. The following declares a rectangular two dimensional array, where the dimensions are 3 × 2:

int[,] intArray = new int[3, 2]; // 2D array

This array consists of three rows and two columns, the index values range from 0, 0 to 2, 1

Let’s look at the indexes for the above array. The element names in row 0 all have a first index of 0, and the element names in column 1 all have a second index of 1.

To assign values to the elements of a rectangular array, you can use one statement for each element. These statements assign values to the elements of the intArray array that was created by the previous statement.

intArray[0, 0] = 1;
intArray[0, 1] = 2;
intArray[1, 0] = 3;
intArray[1, 1] = 4;
intArray[2, 0] = 5;
intArray[2, 1] = 6;

Alternatively, you can assign values at the same time when declaring a two dimensional array. Use curly braces to indicate the different dimensions.

int[,] intArray = { { 1, 2 }, { 3, 4 }, { 5, 6 } };

To fetch a value from a specific placeholder you have to specify the dimension and the index within that dimension. The index positions are used inside indexer ([ ]) when retrieving the value from an array.

intArray[0, 1]; // return 2

Above statement gets the value 2 from the 2nd column of the 1st row, which displays the value of the element [0, 1].

intArray[2, 1]; // return 6

Above statement gets the value 6 from the 2nd column of the 3rd row, which displays the value of the element [2, 1].

You can access a value of an indexed array element by using indexer ([ ]) and then assign a value to it with assignment operator (=).

intArray[0, 1] = 20;

Above statement assigns a value 20 to the 2nd column of the 1st row, which updates the value of the element [0, 1] from 2 to 20.

intArray[2, 1] = 60;

Above statement assigns a value 60 to the 2nd column of the 3rd row, which updates the value of the element [2, 1] from 6 to 60.

Run Demo

3 by 2 Array of Strings

You can declare a 2-dimensional array of strings as

string[,] fruits = { { "Apple", "Banana" }, { "Orange", "Papaya" }, { "Apricot", "Cherry" } };

Run Demo

Example 2: Rectangular 4 by 2 Array

The following declares a rectangular two dimensional array, where the dimensions are 4 × 2:

char[,] charArray = new char[4, 2]; // 2D array

This array consists of four rows and two columns, the index values range from 0, 0 to 3, 1

Indexes for the above array.

To assign values to the elements of a rectangular array, you can use one statement for each element.

charArray[0, 0] = 'A';
charArray[0, 1] = 'B';
charArray[1, 0] = 'C';
charArray[1, 1] = 'D';
charArray[2, 0] = 'E';
charArray[2, 1] = 'F';
charArray[3, 0] = 'G';
charArray[3, 1] = 'H';

Alternatively, you can assign values at the same time when declaring a two dimensional array.

char[,]charArray = { { 'A', 'B' }, { 'C', 'D' }, { 'E', 'F' }, { 'G', 'H' } };

Specify the dimension and the index to fetch a value from a specific placeholder. The index positions are used inside indexer ([ ]) when retrieving the value from an array.

charArray[1, 0]; // return C

Above statement gets the value C from the 1st column of the 2nd row, which displays the value of the element [1, 0].

charArray[3, 1]; // return H

Above statement gets the value H from the 2nd column of the 4th row, which displays the value of the element [3, 1].

You can access a value of an indexed array element by using indexer ([ ]) and then assign a value to it.

charArray[1, 0] = 'K';

Above statement assigns a value ‘K’ to the 1st column of the 2nd row, which updates the value of the element [1, 0] from ‘C’ to ‘K’.

charArray[3, 1] = 'L';

Above statement assigns a value ‘L’ to the 2nd column of the 4th row, which updates the value of the element [3, 1] from ‘H’ to ‘L’.

Run Demo

Example 3: Rectangular 4 by 1 Array

The following declares a rectangular two dimensional array, where the dimensions are 4 × 1:

string[,] strArray = new string[4, 1]; // 2D array

This array consists of four rows and one column, the index values range from 0, 0 to 3, 0

Indexes for the above array.

To assign values to the elements of a rectangular array, you can use one statement for each element.

strArray[0, 0] = "Apple";
strArray[1, 0] = "Banana";
strArray[2, 0] = "Orange";
strArray[3, 0] = "Papaya";

Alternatively, you can assign values at the same time when declaring a two dimensional array.

string[,]strArray = { { "Apple" }, { "Banana" }, { "Orange" }, { "Papaya" } };

Specify the dimension and the index to fetch a value from a specific placeholder. The index positions are used inside indexer ([ ]) when retrieving the value from an array.

strArray[1, 0]; // return Banana

Above statement gets the value Banana from the 2nd row of the column, which displays the value of the element [1, 0].

strArray[3, 0]; // return Papaya

Above statement gets the value Papaya from the 4th row of the column, which displays the value of the element [3, 0].

You can access a value of an indexed array element by using indexer ([ ]) and then assign a value to it.

strArray[1, 0] = "Apricot";

Above statement assigns a value “Apricot” to the 2nd row of the column, which updates the value of the element [1, 0] from “Banana” to “Apricot”.

strArray[3, 0] = "Cherry";

Above statement assigns a value “Cherry” to the 4th row of the column, which updates the value of the element [3, 0] from “Papaya” to “Cherry”.

Run Demo

Array Method

Method Description
GetLength(dimension) Gets the number of elements in the specified dimension of an array.

Getlength Method of a Rectangular Array

To get the number of elements in a dimension of an array.

arrayName.GetLength(dimensionIndex)

Run Demo

Processing Array Using Nested for Loops

Never hardcode total number elements, when you want to iterate through the array. Always use properties or methods such as Length and GetLength to determine the total number of iterations needed. Let’s look at the following examples.

Example 1: 3 by 2 Array

string display = string.Empty;

int[,] intArray = { 
  { 1, 2 }, 
  { 3, 4 }, 
  { 5, 6 } 
};

for (int row = 0; row < intArray.GetLength(0); row++)
{
    for (int column = 0; column < intArray.GetLength(1); column++)
    {
        //Console.WriteLine(intArray[row, column]);
        // OR
        display += intArray[row, column] + " ";
    }

    display += "\n";
}

Console.WriteLine(display);

Run Demo

OUTPUT

1 2
3 4
5 6

First, declared and initialized rectangular intArray variable. On the left side of the declaration, single comma (,) within square brackets indicate that the array is two-dimensional, where the dimensions are 3 × 2 (3 rows and 2 columns). The array is two-dimensional that’s why you need to use 2 separate for loops to iterate through each dimension. Outer for loop is to get the number of rows by calling GetLength method and passing 0 for the 1st dimension and nested for loop, which gets the number of columns for each row by passing 1 for the length of 2nd dimension.
The line Console.WriteLine(intArray[row, column]); simply prints out each element to the console. You use variable intArray with the loop counter row for rowIndex and column for columnIndex within square brackets [ ] when retrieving the individual value from an array element.

Example 2: 4 by 2 Array

string display = string.Empty;

char[,] charArray = { 
  { 'A', 'B' }, 
  { 'C', 'D' }, 
  { 'E', 'F' }, 
  { 'G', 'H' } 
};

for (int row = 0; row < charArray.GetLength(0); row++)
{
    for (int column = 0; column < charArray.GetLength(1); column++)
    {
        display += charArray[row, column] + " ";
    }

    display += "\n";
}

Console.WriteLine(display);

Run Demo

OUTPUT

A B
C D
E F
G H

Example 3: 4 by 1 Array

string display = string.Empty;

string[,] strArray = { 
  { "Apple" }, 
  { "Banana" }, 
  { "Orange" }, 
  { "Papaya" } 
};

for (int row = 0; row < strArray.GetLength(0); row++)
{
    for (int column = 0; column < strArray.GetLength(1); column++)
    {
        display += strArray[row, column] + " ";
    }

    display += "\n";
}

Console.WriteLine(display);

// OR

for (int row = 0; row < strArray.GetLength(0); row++)
{
   Console.WriteLine(strArray[row, 0]);
}

Run Demo

OUTPUT

Apple
Banana
Orange
Papaya

Rectangular Array in Short

  • Declared using comma within the set of brackets followed by the data type
  • Each dimension is separated by a comma
  • Data is stored in a tabular form (fixed rows/columns) which is also known as matrix
  • Sometimes referred to as two-dimensional array (2D)
  • Use the nested for loops to iterate through the rows and columns of a rectangular array

C# Reference | Microsoft Docs

Sending
User Rating 0 (0 vote)