Lesson # 10. Theory
Lecture in pdf format
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:
- Array Initialization:
- Accessing array elements:
- Getting the value of a particular array element and assigning it to a variable:
- Getting the total count of elements (or the length of a given dimension):
- Getting the number of rows and columns:
int[,] arr = new int[5, 3]; |
// 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; |
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 |
int elementValue = arr1[2, 1]; |
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 |
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
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 marked in red color:
(1, 2) (3, 4) (5, 6)
Expected output:
The array: 1 2 3 4 5 6 1-st element = 3, 2-nd element = 5
[Solution and Project name: Lesson_10Lab1
, file name L10Lab1.cs
]
✍ How To Do:
- Create a new project with a name and filename as it is given in the task.
- Include the following library not to print
console
class:
using System.Console;
arr2d
we can use the statement int[,] arr2d;
. But we will initialize the array with values at once. So, within the Main
method you have to enter the code:1, 2}, {3, 4}, {5, 6} };[,] arr2d= { {
Now we have the two-dimensional array with values as it is given in the task.
for ( i = 0; i < arr2d.GetLength(0); i++) { for ( j = 0; j < arr2d.GetLength(1); j++) { Console.Write($"{arr2d[i, j]} "); } Console.WriteLine(); }
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]
. Console.WriteLine($"1-st element = {arr2d[1,0]}, 2-nd element = {arr2d[2, 0]}");
.cs
to the moodle system.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:
- Print out a 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
and11
). - Print out the values of the temperature of all weather stations during the 2nd day (
for
loop is needed). - Print out the values of the temperature of all weather stations during all days.
- Calculate the average temperature at the 3rd weather station (
for
loop is needed). - Print out the days and the weather stations’ numbers where the temperature was in the range of 24—26 degrees Celsius.
Expected output:
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
[Solution and Project name: Lesson_10Task1
, file name L10Task1.cs
]
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:
new [2, 3];[,] arr=
Note 2: to input the values of 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++) { ... } }
Expected output:
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
[Solution and Project name: Lesson_10Task2
, file name L10Task2.cs
]
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.
Expected output:
Please enter 12 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
[Solution and Project name: Lesson_10Task3
, file name L10Task3.cs
]
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); |
minValue
and maxValue
are the boundaries of the range of generated numbers.Expected output:
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
[Solution and Project name: Lesson_10Lab2
, file name L10Lab2.cs
]
✍ How To Do:
- Create a new project with a name and a filename as it is in the task.
- Include the following library not to print
console
class:
using static System.Console;
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"); rows = int.Parse(ReadLine()); Console.WriteLine("please enter the number of columns"); columns = int.Parse(ReadLine());
[,] matrix = [rows,columns];
-10; maxValue=10;minValue=
To make the programming process more productive we will use ReSharper (to initialize a 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);
Alt+Enter
or click the bulb. We must choose the item «Generate method Program.FillMatrix».FillMatrix(-10, maxValue = 10);[,] matrix, minValue =
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
Random rand = new Random();
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(); }
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.
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.CTRL+a, CTRL+k, CTRL+F
keys to format your code.Ctrl+M (twice
). To expand it again use the same shortcut snippet Ctrl+M (twice)
.CTRL+F5
to see the output.L10Lab2.cs
to the moodle system.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 FindMinMaxArr( [,] matrix, ref min, ref max)
Note 2: To find a minimum and a maximum you can see as you did it in the Lesson # 5 -> lab 4.
Expected output:
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
[Solution and Project name: Lesson_10Task4
, file name L10Task4.cs
]
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.
Expected output:
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
[Solution and Project name: Lesson_10Lab3
, file name L10Lab3.cs
]
✍ How to do:
- Create a new project with a name and a filename 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 = int[3, 4];
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: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); } } }
PrintMatrix
method. The method will take one parameter, it is the matrix itself: 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(); } }
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.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);
... Console.WriteLine("please enter the number of the columns to swap (first column is 0):"); int col1= int. (Console.ReadLine()); int col2 = int. (Console.ReadLine());
ChangeColumns
to swap entered column numbers of a matrix:static 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; // or if you use Visual studio 2019: // (matrix[i, col1], matrix[i, col2]) = (matrix[i, col2], matrix[i, col1]); } }
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.main
function. And after, call the PrintMatrix
method to see the result:... ChangeColumns(matrix, col1, col2); Console.WriteLine("The resulting matrix:"); PrintMatrix(matrix);
CTRL+F5
to see the output.L10Lab3.cs
to the moodle system.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.
Expected output:
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
[Solution and Project name: Lesson_10Task5
, file name L10Task5.cs
]
To do: Create a user defined method (extension 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 method. Note that you will need to create a class in the same file to have the method in it.
Note: FindProductOfColumn
signature must be as follows (see pdf file of lecture #8):
public static void FindProductOfColumn(this int[,] matrix, int M,out int product) |
Expected output:
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
[Solution and Project name: Lesson_10Task6
, file name L10Task6.cs
]
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:To do: Create square matrix M-by-M (M
is inputted). Calculate a sum of its elements within an antidiagonal (secondary diagonal).
Expected output:
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
[Solution and Project name: Lesson_10Lab4
, file name L10Lab4.cs
]
✍ How to do:
- Create a new project with a name and a filename 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. (Console.ReadLine());
M
-by-M
. Declare a matrix within the Main
function:int[,] matrix = int[M, M];
FillMatrix
method from the previous Lab and paste it after the closing curly brace of the Main
function.PrintMatrix
from the previous Lab and paste it after the FillMatrix
method.AntidiagonalSum
which will calculate the sum of the antidiagonal elements.int AntidiagonalSum(int[,] matrix) { ... }
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]; } } }
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;
Main
function:int result = AntidiagonalSum(matrix); Console.WriteLine($"the sum of the secondary diagonal is {result}");
CTRL+F5
to see the output..cs
to the moodle system.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
.
Expected output:
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
[Solution and Project name: Lesson_10Task7
, file name L10Task7.cs
]
Extra tasks
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) |
Expected output:
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
[Solution and Project name: Lesson_10ExTask1
, file name L10ExTask1.cs
]
To do: Two matrices of the same size are given (create a method to fill the matrices with random integers). Calculate their sum by creating a new matrix for this purpose.
Note: the signature of the method must be as following:
static int[,] SumMat(int[,] a, int[,] b) |
Expected output:
Matrix 1: -3 8 3 -9 -6 4 6 4 -2 Matrix 2: 4 -4 1 -5 1 -1 4 8 -10 Result matrix: 1 4 4 -14 -5 3 10 12 -12
[Solution and Project name: Lesson_10ExTask2
, file name L10ExTask2.cs
]