C-SHARP - 4.1 Advanced tables
This video dives deeper into arrays in C#. A reminder: an array holds a fixed number of values of the same type, all referenced by an index that starts at 0. We start by creating two single-dimension arrays: one int[] initialised between braces and one string[] initialised cell by cell using the index. So far we have only used one-dimensional arrays, which represent a single row of columns. C# also lets us build multidimensional arrays, where each element can itself contain several values: the most common is a two-dimensional array with rows and columns, perfect for representing a matrix or a grid.
To declare a 2D array we type var tab = new string[3, 3]: the first number is the row count, the second the column count. To initialise it inline we open braces, then for each row we open another pair of braces with the values in order. Accessing a value now requires two indexes: tab[row, column]. With tab[1, 2] we ask for the value at row 1, column 2.
var tab = new string[3, 3]
{
{ "Jason", "Tibo", "Tom" },
{ "Marc", "Paul", "Anna" },
{ "Lou", "Eli", "Sam" }
};
for (int i = 0; i < 3; i++)
{
Console.WriteLine(string.Format("Group {0}", i + 1));
for (int j = 0; j < 3; j++)
{
Console.WriteLine(tab[i, j]);
}
}
Nested loops
- The outer loop iterates over the rows (variable
i). - The inner loop iterates over the columns of the current row (variable
j). - Inside the inner loop we read
tab[i, j]to get every value of the matrix.
To display all the names we use nested loops: a first for walks through the rows, and inside it a second for walks through the columns. At each iteration of the inner loop we print tab[i, j]. Imagine a character climbing 10 stairs to reach a floor and 5 floors in total: the outer loop counts the floors, the inner loop counts the stairs of the current floor. That is exactly the spirit of nested loops on a 2D array.