Lesson # 10. A two-dimensional array

Дата изменения: 6 мая 2020
Programming on c sharp in Microsoft Visual Studio. Creating A Two-dimensional Array.

Lesson # 10. Theory

A two-dimensional array

    Arrays can have more than one dimension. In the example below, we have a declaration that creates a two-dimensional array of five rows and three columns (5-by-3).

  • Array Declaration:
  • int[,] arr = new int[5, 3];
  • Array Initialization:
  • // 1. Initialization the array upon declaration:
    int[,] arr1 = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
    // The same array with dimensions specified:
    int[,] arr1 = new int[4, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
     
    // 2. Initialization without specifying the rank:
    int[,] arr2 = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
     
    // 3. Initialization after declaration:
    int[,] arr;
    arr = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
     
    // Assigning a value to a particular array element:
    arr[2, 1] = 25;
  • Accessing array elements:
  • int[,] arr1 = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
    System.Console.WriteLine(arr1[0, 0]); //1
    System.Console.WriteLine(arr1[0, 1]); //2
    System.Console.WriteLine(arr1[1, 0]); //3
    System.Console.WriteLine(arr1[1, 1]); //4
    System.Console.WriteLine(arr1[3, 0]); //7
  • Getting the value of a particular array element and assigning it to a variable:
  • int elementValue = arr1[2, 1];
  • Getting the total count of elements (or the length of a given dimension):
  • int[,] arr = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
    var arrayLength = arr.Length;
    var total = 1;
    for (int i = 0; i < arr.Rank; i++) {
        total *= arr.GetLength(i);
    }
    System.Console.WriteLine("{0} equals {1}", arrayLength, total); // 8 equals 8
  • Getting the number of rows and columns:
  • int[,] matrix = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
    int r=matrix.GetLength(0); // rows
    int c=matrix.GetLength(1); // columns

Labs and tasks

Lab 1. Two-dimensional array
To do: Initialize a two-dimensional array* named arr2d with given integer values, they are ((1, 2); (3, 4); (5, 6)).
1) First, output all the elements of the array.
2) After, output the following elements to the Console window (the elements to output are marked in blue color):

(1, 2)
(3, 4) 
(5, 6)

  

* A two-dimensional array can be called matrix.

 
[Solution and Project name: Lesson_10Lab1, file name L10Lab1.cs]

The result examples:

The array:
1  2
3  4
5  6
1-st element = 3, 2-nd element = 5

✍ How To Do:

  • Create a new project with a name and file name as it is given in the task.
  • Include the following library not to print console class:
  • using static System.Console;
    
  • To declare a two-dimensional array of integer type called arr2d we can use the statement int[,] arr2;. But we will initialize the array with values at once. So, within the Main method you have to enter the code:
  • int[,] arr2d= { {1, 2}, {3, 4}, {5, 6} };
    

    Now we have the two-dimensional array with values as it is given in the task.

  • To output all the array elements, we must use nested loops, the outer loop must iterate over the rows and the inner loop must iterate over the columns of the elements in each row. Within the inner loop you have to output every element. To get access to each element by its index you must use the counters of the loop as the indexes of the element:
  • for (int i = 0; i < arr2d.GetLength(0); i++)
                {
                    for (int j = 0; j < arr2d.GetLength(1); j++)
                    {
                        Console.Write($"{arr2d[i, j]}  ");
                    }
                    Console.WriteLine();
                }
    
    To output the element to the Console window we need to understand which row and column the element is in. Note, that indexes start at 0 value. So, the element with a value of 3 can be accessed as arr2[1,0] (where 1 is a row and 0 is a column), and the element with a value of 5 can be accessed as arr2[2,0].
  • Output the elements:
  • Console.WriteLine($"1-st element = {arr2d[1,0]}, 2-nd element = {arr2d[2, 0]}");
    
  • Run the application again and check the output.
  • Experiment with different values to see the output.
  • Add comments with the text of the task and save the project. Download file .cs to the moodle system.


You can watch the video of the explanation:

Task 1:
The air temperature values for 4 days are given, they are taken from three weather stations located in different regions of the country:

Station number 1-st day 2-nd day 3-d day 4-th day
1 -8 -14 -19 -18
2 25 28 26 20
3 11 18 20 25

That is, in a two-dimensional array it would look like this:

t[0,0]=-8; t[0,1]=-14; t[0,2]=-19; t[0,3]=-18;
t[1,0]=25; t[1,1]=28; t[1,2]=26; t[1,3]=20;
t[2,0]=11; t[2,1]=18; t[2,2]=20; t[2,3]=25;

  
Note: Initialization of the array:

 int [,] t = {
                {-8,-14,-19,-18},
                { 25,28, 26, 20},
                { 11,18, 20, 25}
                };

To do:

  1. Output value of the temperature at the 2nd weather station during the 4th day and at the 3rd weather station during the 1st day (your result must be 20 and 11).
  2. Output the values of the temperature of all weather stations during the 2nd day (for loop is needed).
  3. Output the values of the temperature of all weather stations during all days.
  4. Calculate the average temperature at the 3rd weather station (for loop is needed).
  5. Output the days and the weather stations’ numbers where the temperature was in the range of 2426 degrees Celsius.

     
[Solution and Project name: Lesson_10Task1, file name L10Task1.cs]
  
The resulting example:

1-st task: 20  and  11
2-nd task: 25 28 26 20
3-d task:
-8  -14  -19  -18
25   28   26   20
11   18   20   25

4-th task: 18
5-th task:
station number 1  day 0
station number 1  day 2
station number 2  day 3



You are welcome to watch the video for this task:


Task 2:
To do: Ask user to input the values of the elements of a two-dimensional array 2-by-3 ([2,3]). Calculate an addition (a sum) of the elements.
   
Note 1: to declare an array with two rows and three columns use the code: 

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

 
Note 2: to input the values for the elements and iterate over the array the nested loop is needed:

for (int i = 0; i < 2; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                   ...
                }
            }

[Solution and Project name: Lesson_10Task2, file name L10Task2.cs]
  
The resulting example:

Please enter 6 values for the matrix 2 by 3
2
5
1
6
7
8
The array:
2  5  1
6  7  8
the sum =  29





Task 3:
To do: Ask user to input the values of the elements of a two-dimensional array 4-by-3 ([4,3]). Count positive elements within the array.
   

[Solution and Project name: Lesson_10Task3, file name L10Task3.cs]
  
The resulting example:

Please enter 6 values for the matrix 4-by-3
2  5  -1  6  7  8  1  8  6  -3  1  -6
The array:
2   5  -1
6   7   8
1   8   6
-3  1  -6
number of positive = 9


Lab 2. Using Random function while working with two-dimensional arrays

To do: Create a method called FillMatrix to fill an array with random numbers in the range from -10 to 10.

Note: The signature of the FillMatrix method must be as follows:

FillMatrix(matrix, minValue, maxValue);

[Solution and Project name: Lesson_10Lab2, file name L10Lab2.cs]

The result examples:

please enter the number of rows
3
please enter the number of columns
4
The array:
-10 -7 -3 -4
-6   1  4  0
-5  -8 -1 -5


✍ How To Do:

  • Create a new project with a name and a file name as it is in the task.
  • Include the following library not to print console class:
  • using static System.Console;
    
  • Within the Main function ask the user to enter how many rows and columns there will be. Assign the entered values to variables:
  • ...
    Console.WriteLine("please enter the number of rows");
    int rows = int.Parse(ReadLine());
    Console.WriteLine("please enter the number of columns");
    int columns = int.Parse(ReadLine());
    
  • After, we must declare a matrix:
  • int[,] matrix = new int[rows,columns];
    
  • Initialize variables for the boundaries of random number generator:
  •   int minValue=-10;
      int maxValue=10;
    

    To make the programming process more productive we will use ReSharper (to initialize a method):

  • Now we will call the method FillMatrix from within the Main function (even though we haven’t created it yet). Enter the following code within the curly braces of Main():
  • FillMatrix(matrix, minValue, maxValue);
    
  • The name of the method is underlined. When you put your cursor where the underline is you will see the icon of a yellow bulb from the left side or below. Now we can activate the ReSharper comments using Alt+Enter or click the bulb. We must choose the item «Generate method Program.FillMatrix».
  • The signature of the method has appeared.
  • Change the code:
  • FillMatrix(int[,] matrix, int minValue = -10, int maxValue = 10); 
    
  • The method has three parameters:
  • matrix — a declared matrix without initialization;
    minValue — to set the lower bound for the function Random, it has an initial value of -10
    maxValue — to set the upper bound for the function Random, it has an initial value of 10

  • Within the created function instantiate random number generator using system-supplied value as seed:
  • Random rand = new Random();
    
  • Generate and display random integer values of the matrix, using the boundaries (parameters minValue and maxValue):
  • ...
    for (int i = 0; i < matrix.GetLength(0); i++)
                {
                    for (int j = 0; j < matrix.GetLength(1); j++)
                    {
                        matrix[i, j] = rand.Next(minValue, maxValue);
                        Write(matrix[i, j].ToString().PadLeft(4));
                    }
                    WriteLine();
                }
    
    Note, that matrix.GetLength(0) means the number of rows and matrix.GetLength(1) means the number of columns.
    To print out the elements in straight lines, we’ve converted them into a string type and used PadLeft method, which returns a new string that right-aligns the characters in this instance by padding them on the left for a specified total length.
    We must use nested loops to iterate over the rows and columns. The identifications for the counters of the loops have to be different, we use identifications i and j for them. The method GetLength(0) returns the number of the rows within the matrix, the method GetLength(1) returns the number of the columns.
  • Press the CTRL+a, CTRL+k, CTRL+F keys to format your code.
  • To collapse the code of the method for a while you can use Ctrl+M (twice). To expand it again use the same shortcut snippet Ctrl+M (twice).
  • Run the program by pressing CTRL+F5 to see the output.
  • Add comments with the text of the task and save the project. Download file L10Lab2.cs to the moodle system.




Task 4:
To do: Create a method called FillMatrix to fill an array with random numbers in the range from -15 to 15. Create one more function to find a minimum and maximum elements of the array (FindMinMaxArr).
   
Note 1: The signature of the FindMinMaxArr function must be: 

private static void FindMinMaxArr(int[,] matrix, ref int min, ref int max)

  
Note 2: To find a minimum and a maximum you can see as you did it in the Lesson # 5 -> lab 4.

[Solution and Project name: Lesson_10Task4, file name L10Task4.cs]
  
The resulting example:

please enter the number of rows
4
please enter the number of columns
5
The array:
10   2   9  3  4
-3 -10 -14 -4  2
 2  -9  11  3 -10
-1 -13  -5 -2  3
min = -14, max = 11




Lab 3. Swapping some columns of a matrix

To do: Create a method called ChangeColumns to swap some columns of a matrix (3-by-4) (the order numbers of columns to swap are inputted).

Note: Besides the method ChangeColumns you have to create a method FillMatrix to fill a matrix with random integers, and a method PrintMatrix to print the elements of a matrix.

[Solution and Project name: Lesson_10Lab3, file name L10Lab3.cs]

The result examples:

The array 3 x 4:
-10 -7 -3 -4
-6   1  4  0
-5  -8 -1 -5
please enter the number of the columns to swap (the first column is 0):
1
2
The resulting matrix:
-10 -3 -7 -4
-6   4  1  0
-5  -1 -8 -5


✍ How to do:

  • Create a new project with a name and a file name as it is in the task.
  • We’re going to create a matrix with three rows and four columns. Declare a matrix within the Main function:
  • int[,] matrix = new int[3, 4];
  • Copy the code of the FillMatrix from the Lab 2. And paste it into the proper place of the current lab. Or you can create it again. After, you will have:
  • static void FillMatrix(int[,] matrix, int minValue = -10, int maxValue = 10) {
                Random rand = new Random();
                for (int i = 0; i < matrix.GetLength(0); i++)
                {
                    for (int j = 0; j < matrix.GetLength(1); j++)
                    {
                        matrix[i, j] = rand.Next(minValue, maxValue);
                     }
                }
            }
    
  • To print out the elements of the matrix we’re going to create a PrintMatrix method. The method will take one parameter, it is the matrix itself:
  • static void PrintMatrix(int[,] m)
            {
                for (int i = 0; i < m.GetLength(0); i++)
                {
                    for (int j = 0; j < m.GetLength(1); j++)
                    {
                       Console.Write(m[i, j].ToString().PadLeft(4));
                    }
                    Console.WriteLine();
                }
            }
    
    To print out the elements in straight lines, we’ve convert them into a string type and used PadLeft method, that returns a new string that right-aligns the characters in this instance by padding them on the left for a specified total length.
  • Now, within the Main function we’re going to call the methods: first — the FillMatrix method and after — the PrintMatrix method.
  • ...
    FillMatrix(matrix);
    Console.WriteLine("The array 3 x 4: ");
    PrintMatrix(matrix);
    
  • After, we have to prompt the user input two integers — the column numbers we’re going to swap:
  • ...
    Console.WriteLine("please enter the number of the columns to swap (first column is 0):");
    int col1= int.Parse(Console.ReadLine());
    int col2 = int.Parse(Console.ReadLine());
    
  • Create a method ChangeColumns to swap entered column numbers of a matrix:
  • static void ChangeColumns(int[,] matrix, int col1, int col2)
            {
                System.Diagnostics.Debug.Assert((col1 < matrix.GetLength(1)) && (col2 < matrix.GetLength(1)), "the number column is out of the range of the matrix!");
                for (int i = 0; i < matrix.GetLength(0); i++)
                {
                    int temp = matrix[i, col1];
                    matrix[i, col1] = matrix[i, col2];
                    matrix[i, col2] = temp;
                }
            }
    
    The counter of the loop i iterates over the rows of the matrix, meanwhile each element of col1 is replaced with the element of col2 in each row, and vice versa.
    System.Diagnostics.Debug.Assert is used to raise an exception if the inputted number is greater than the quantity of the columns.
  • Call the method within the main function. And after, call the PrintMatrix method to see the result:
  • ...
    ChangeColumns(matrix, col1, col2);
    Console.WriteLine("The resulting matrix:");
    PrintMatrix(matrix);
    
  • Run the program by pressing CTRL+F5 to see the output.
  • Add comments with the text of the task and save the project. Download file L10Lab3.cs to the moodle system.




Task 5:
To do: Create a method called PlaceZero which replaces some elements of a matrix (5-by-5) with 0. Take a look at the result example below to get to know which elements should be replaced.
   
Note 1: Create methods to fill and print out a matrix.
Note 2: The signature of the PlaceZero function must be: 

static void PlaceZero(int[,] matrix)

  
Note 3: To replace elements with 0 you have to use loops.

[Solution and Project name: Lesson_10Task5, file name L10Task5.cs]
  
The resulting example:

The matrix:
10 2  9  3  6 
3  10 14 4  8
2  9  11 3  2
1  13 5  2  7
12 3  11 4  5

The resulting array:
0  0  0  0  0 
0  10 14 4  0
0  9  11 3  0
0  13 5  2  0
0  0  0  0  0





Task 6:
To do: Create a method called FindProductOfColumn to find a product of the M-th column elements of a matrix (3-by-4) (M is entered). M is out parameter of the matrix.

Note: FindProductOfColumn signature must be as follows:

static void FindProductOfColumn(int[,] matrix, int M,out int product)

[Solution and Project name: Lesson_10Task6, file name L10Task6.cs]

The result examples:

The matrix:
-10 -3 -7 -4
-6   4  1  0
-5  -1 -8 -5
please enter the number of the columns (the first column is 0):
2
The product of 2-th column elements is  -64



Main diagonal and Antidiagonal
  
In linear algebra, the main diagonal of a matrix A is the collection of entries Ai,j where i=j. All off-diagonal elements are zero in a diagonal matrix. The following three matrices have their main diagonals indicated by red 1’s:

The antidiagonal (sometimes counter diagonal, secondary diagonal, trailing diagonal, minor diagonal, or bad diagonal) of a dimension N square matrix B, is the collection of entries Bi,j such that i+j=N+1 for all 1<=i,j<=N. But if i and j start with zero, in that case we have i+j=N-1. That is, it runs from the top right corner to the bottom left corner:


Lab 4. Working with Antidiagonal

To do: Create square matrix M-by-M (M is inputted). Calculate a sum of its elements within an antidiagonal (secondary diagonal).

[Solution and Project name: Lesson_10Lab4, file name L10Lab4.cs]

The result examples:

Please enter the number for a matrix dimension:
3 
The matrix 3-by-3:
10 -7 -3 
6   1  4 
5  -8 -1 
the sum of the secondary diagonal is 3


✍ How to do:

  • Create a new project with a name and a file name as it is in the task.
  • Ask the user to input a matrix dimension and assign an entered number to a variable M:
  • Console.WriteLine("Please enter the number for a matrix dimension:");
    int M = int.Parse(Console.ReadLine());
    
  • We're going to create a matrix M-by-M. Declare a matrix within the Main function:
  • int[,] matrix = new int[M, M];
    
  • Copy the code of the FillMatrix method from the previous Lab and paste it after the closing curly brace of the Main function.
  • Copy the code of the PrintMatrix from the previous Lab and paste it after the FillMatrix method.
  • Create a method called AntidiagonalSum which will calculate the sum of the antidiagonal elements.
  • static int AntidiagonalSum(int[,] matrix) 
    {
    ...
    }
    
  • Note, that antidiagonal elements are such as i+j=M-1. To iterate over the matrix elements we're going to use nested loops:
  • ...
    int sum = 0;
    for (int i = 0; i < matrix.GetLength(0); i++)
                {
                    for (int j = 0; j < matrix.GetLength(1); j++)
                    {
                        if ((i+j == M-1)
                           {
                             sum+ = matrix[i,j];
                           }
                     }
                }
    
  • We're going to return the sum into the caller, which is why we use the return keyword. Place it after the loops, right before the closing curly brace of our method:
  • ...
    return sum;
    
  • Call the method and print out the results within the Main function:
  • int result = AntidiagonalSum(matrix);
    Console.WriteLine($"the sum of the secondary diagonal is {result}");
    
  • Run the program by pressing CTRL+F5 to see the output.
  • Add comments with the text of the task and save the project. Download file .cs to the moodle system.

Task 7:
To do: Create square matrix M-by-M (M is inputted). Calculate a product of its elements within a main diagonal.

Note: a main diagonal elements are such as i=j.

[Solution and Project name: Lesson_10Task7, file name L10Task7.cs]

The result examples:

Please enter the number for a matrix dimension:
3 
The matrix 3-by-3:
10 -7 -3 
6   1  4 
5  -8 -1 
the product of the main diagonal is -10

Extra tasks

Extra Task 1:
To do: Positive integers M and N are inputted. Create a method FillMatrix to fill the elements of an integer matrix M-by-N; all the elements of the J-th column have the value X*J (J - number of a column, J = 1, ..., N), where X is a parameter of the method.
  
Note: the signature of the method must be as following:

static int[,] FillMatrix(int M, int N, int X)

 
[Solution and Project name: Lesson_10ExTask1, file name L10ExTask1.cs]

The result examples:

please enter the number of rows:
3
please enter the number of columns
4
Please enter the number to multiply by:
3 
The matrix 3-by-3:
3 6 9 12
3 6 9 12
3 6 9 12 


Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

*
*


Вставить формулу как
Блок
Строка
Дополнительные настройки
Цвет формулы
Цвет текста
#333333
Используйте LaTeX для набора формулы
Предпросмотр
\({}\)
Формула не набрана
Вставить