Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this nested loop output a list separated into 3 sections with 3 words in each section?

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();
        }
    }
}```
like image 240
Ice Wazowski Avatar asked Dec 20 '25 21:12

Ice Wazowski


1 Answers

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 
like image 157
Idle_Mind Avatar answered Dec 22 '25 11:12

Idle_Mind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!