Issue
I'm very new to C#. I was curious on how this block of code printed out 3 separate lines with the 3 words in the arrays. Could someone explain how it works?
using System;
namespace MyFirstProgram
{
class Program
{
static void Main(string[] args)
{
String[,] parkingLot = {{ "Mustang", "F-150", "Explorer" }, { "Corvette", "Camaro", "Silverado" }, { "Corolla", "Camry", "Rav4" }};
for(int i = 0; i < parkingLot.GetLength(0); i++)
{
for (int j = 0; j < parkingLot.GetLength(1); j++)
{
Console.Write(parkingLot[i, j] + " ");
}
Console.WriteLine();
}
Console.ReadKey();
}
}
}```
Solution
The GetLength() method returns the size of the dimension passed in:
Gets a 32-bit integer that represents the number of elements in the specified dimension of the Array.
Notice the first call gets passed a zero:
parkingLot.GetLength(0)
This returns the number of ROWS in the 2D array.
The second call is passed a one:
parkingLot.GetLength(1)
Which tells you the number of COLUMNS in the 2D array.
Perhaps this example will illustrate the concept better:
String[,] parkingLot = {
{ "a", "b", "c" },
{ "1", "2", "3" },
{ "red", "green", "blue" },
{ "cat", "dog", "fish"},
{ "A1", "B2", "C3"}
};
for(int row = 0; row < parkingLot.GetLength(0); row++) // 5 rows
{
for (int col = 0; col < parkingLot.GetLength(1); col++) // 3 columns
{
Console.Write(parkingLot[row, col] + " ");
}
Console.WriteLine();
}
Output:
a b c
1 2 3
red green blue
cat dog fish
A1 B2 C3
Answered By - Idle_Mind Answer Checked By - Timothy Miller (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.