Guide to the Language
Download 2 Mb. Pdf ko'rish
|
C sharp
- Bu sahifa navigatsiya:
- Jagged Arrays
- CHAPTER 7 Conditionals Conditional statements are used to execute different code blocks based on different conditions. If Statement
Rectangular Arrays
There are two kinds of multi-dimensional arrays in C#: rectangular and jagged. A rectangular array has the same length of all sub-arrays and separates the dimensions using a comma. string[,] x = new string[2, 2]; Chapter 6 arrays 27 As with single-dimensional arrays, they can either be filled in one at a time or all at once during the allocation. x[0, 0] = "00"; x[0, 1] = "01"; x[1, 0] = "10"; x[1, 1] = "11"; string[,] y = { { "00", "01" }, { "10", "11" } }; Jagged Arrays Jagged arrays are arrays of arrays, and they can have irregular dimensions. The dimensions are allocated one at a time and the sub-arrays can therefore be allocated to different sizes. string[][] a = new string[2][]; a[0] = new string[1]; a[0][0] = "00"; a[1] = new string[2]; a[1][0] = "10"; a[1][1] = "11"; It is possible to assign the values during the allocation. string[][] b = { new string[] { "00" }, new string[] { "10", "11" } }; These are all examples of two-dimensional arrays. If you need more than two dimensions, more commas can be added for the rectangular array, or more square brackets for the jagged array. Chapter 6 arrays 29 © Mikael Olsson 2020 M. Olsson, C# 8 Quick Syntax Reference, https://doi.org/10.1007/978-1-4842-5577-3_7 CHAPTER 7 Conditionals Conditional statements are used to execute different code blocks based on different conditions. If Statement The if statement will execute only if the condition inside the parentheses is evaluated to true. The condition can include any of the comparison and logical operators. // Get a random integer (0, 1 or 2) int x = new System.Random().Next(3); if (x < 1) { System.Console.Write(x + " < 1"); } To test for other conditions, the if statement can be extended by any number of else if clauses. Each additional condition will be tested only if all previous conditions are false. else if (x > 1) { System.Console.Write(x + " > 1"); } 30 The if statement can have one else clause at the end, which will execute if all previous conditions are false. else { System.Console.Write(x + " == 1"); } As for the curly brackets, they can be left out if only a single statement needs to be executed conditionally. However, it is considered good practice to include them since they improve readability. if (x < 1) System.Console.Write(x + " < 1"); else if (x > 1) System.Console.Write(x + " > 1"); else System.Console.Write(x + " == 1"); Download 2 Mb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling