PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, August 15, 2022

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

 August 15, 2022     c#, for-loop, multidimensional-array, nested-loops, output     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing