Home

Two-Dimensional Arrays

 

Introduction

The arrays we used so far were made of a uniform series, where all members consisted of a simple list, like a column of names on a piece of paper. Also, all items fit in one list. In some cases, you may want to divide the list in delimited sections. For example, if you create a list of names, you may want part of the list to include family members and another part of the list to include friends. Instead of creating a second list, you can add a second dimension to the list. In other words, you would like to create a list of a list, or one list inside of another list, although the list is still made of items with common characteristics.

A multi-dimensional array is a series of lists so that each list contains its own list. For example, if you create two lists of names, you would have an array of two lists. Each array or list would have its own list or array.

Practical Learning Practical Learning: Introducing Multidimensional Arrays

  1. Create a new Console Application named DepartmentStore4
  2. Change the Program.cs file as follows:
     
    using System;
    
    namespace DepartmentStore4
    {
        class Program
        {
            static int Main(string[] args)
            {
                long ItemID = 0;
                string Description = "Unknown";
                decimal Price = 0.00M;
    
                Console.WriteLine("Receipt");
                Console.WriteLine("Item Number: {0}", ItemID);
                Console.WriteLine("Description: {0}", Description);
                Console.WriteLine("Unit Price:  {0:C}\n", Price);
    
                return 0;
            }
        }
    }
  3. Execute the application to see the result. This would produce:
     
    Receipt
    Item Number: 0
    Description: Unknown
    Unit Price:  $0.00
    
    Press any key to continue . . .
  4. Close the DOS window

Creating a Two-Dimensional Array

The most basic multi-dimensional array is an array of an array, also referred to as two-dimensional. To create a two-dimensional array, declare the array variable as we did earlier but add a comma in the square brackets. The formula you would use is:

DataType[,] VariableName;

The pair of brackets is empty but must contain a comma. There are two ways you can use a two-dimensional array. If you are declaring the array variable but are not ready to initialize it, use the following formula:

DataType[,] VariableName = new DataType[Number1,Number2];

Based on this, type two integers separated by a comma in the right square brackets. Here is an example:

using System;

namespace CSharpLessons
{
    class Exercise
    {
	static void Main()
	{
	    string[,] Members = new string[2,4];
	}
}

In this declaration, the Members variable contains two lists. Each of the two lists contains 4 items. This means that the first list contains 4 items, the second list contains 4 items also. Therefore, the whole list is made of 8  items (2*4=8). Because the variable is declared as a string, each of the 8 items is a string.

You can initialize an array variable when declaring it. To do this, on the right side of the declaration, before the closing semi-colon, type an opening and a closing curly brackets. Inside of the brackets, include a pair of an opening and a closing curly brackets for each internal list of the array. Then, inside of a pair of curly brackets, provide a list of the values of the internal array, just as you would do for a one-dimensional array. Here is an example:

using System;

namespace CSharpLessons
{
    class Exercise
    {
	static void Main()
	{
	    String[,] members = new String[2,4]{
		 {"Celeste", "Mathurin", "Alex", "Germain"},
		   {"Jeremy", "Mathew", "Anselme", "Frederique"}
                 };

            	    Console.WriteLine();
	}
}

If you use this technique to initialize an array, you can omit specifying the dimension of the array.

Practical Learning Practical Learning: Creating a Two-Dimensional Array

  1. To create and use a two-dimensional array, change the file as follows:
     
    using System;
    
    namespace DepartmentStore4
    {
        class Program
        {
            static int Main(string[] args)
            {
                long ItemID = 0;
                string Description = "Unknown";
                decimal Price = 0.00M;
    
                // The first list contains women's items
                // The other contains non-women items
                long[,] ItemNumber = new long[2, 5]{
    		  { 947783, 934687, 973947, 987598, 974937 },
    		  { 739579, 367583, 743937, 437657, 467945 } };
                string[,] ItemName = new string[2, 5]
    	    {
    		{
    		    "Women Double-faced wool coat",
    		    "Women Floral Silk Tank Blouse",
    		    "Women Push Up Bra",
    		    "Women Chiffon Blouse",
    		    "Women Bow Belt Skirtsuit"
    		},
    		{
    		    "Men Cotton Polo Shirt",
    		    "Children Cable-knit Sweater  ",
                        "Children Bear Coverall Cotton",
    		    "Baby three-piece Set         ",
    		    "Girls Jeans with Heart Belt  "
    		}
    	    };
            
    	    decimal[,] UnitPrice = new decimal[2, 5]
    	    {
    		{ 275.25M, 180.05M, 50.00M, 265.35M, 245.55M   },
    	    	{ 45.55M, 25.65M,	28.25M, 48.55M, 19.95M }
    	    };
    		
                Console.WriteLine("Receipt");
                Console.WriteLine("Item Number: {0}", ItemID);
                Console.WriteLine("Description: {0}", Description);
                Console.WriteLine("Unit Price:  {0:C}\n", Price);
    
                return 0;
            }
        }
    }
  2. Save the file

Accessing the Members of a Two-Dimensional Array

To use the members of a two-dimensional array, you can access each item individually. For example, to initialize a two-dimensional array, you can access each member of the array and assign it a value. The external list is zero-based. In other words, the first list has an index of 0, the second list has an index of 1. Internally, each list is zero-based and behaves exactly like a one-dimensional array. To access a member of the list, type the name of the variable followed by its square brackets. In the brackets, type the index of the list, a comma, and the internal index of the member whose access you need. Here is an example:

using System;

namespace CSharpLessons
{
    class Exercise
    {
	static void Main()
	{
	    String[,] members = new String[2,4];

             members[0,0] = "Celeste";
             members[0,1] = "Mathurin";
	     members[0,2] = "Alex";
	     members[0,3] = "Germain";
	     members[1,0] = "Jeremy";
	     members[1,1] = "Mathew";
             members[1,2] = "Anselme";
             members[1,3] = "Frederique";

             Console.WriteLine();
	}
}

Practical Learning Practical Learning: Accessing Members of a Two-Dimensional Array

  1. To retrieve the values of a two-dimensional array, change the file as follows:
     
    using System;
    
    namespace DepartmentStore4
    {
        class Program
        {
            static int Main(string[] args)
            {
                long ItemID = 0;
                string Description = "Unknown";
                decimal Price = 0.00M;
    
                // The first list contains women's items
                // The other contains non-women items
                long[,] ItemNumber = new long[2, 5]
    	    {
    		{ 947783, 934687, 973947, 987598, 974937 },
    		{ 739579, 367583, 743937, 437657, 467945 } };
                string[,] ItemName = new string[2, 5]
    	    {
    	 	{
    		    "Women Double-faced wool coat",
    		    "Women Floral Silk Tank Blouse",
    		    "Women Push Up Bra",
    		    "Women Chiffon Blouse",
    		    "Women Bow Belt Skirtsuit"
    		},
    		{
    		    "Men Cotton Polo Shirt",
    		    "Children Cable-knit Sweater  ",
                        "Children Bear Coverall Cotton",
    		    "Baby three-piece Set         ",
    		    "Girls Jeans with Heart Belt  " } };
                decimal[,] UnitPrice = new decimal[2, 5]{
    		 { 275.25M, 180.05M, 50.00M, 265.35M, 245.55M },
    		 { 45.55M, 25.65M,	28.25M, 48.55M, 19.95M } };
    
                // Order Processing
                try
                {
                    Console.Write("Enter Item Number: ");
                    ItemID = long.Parse(Console.ReadLine());
                }
                catch (FormatException)
                {
    Console.WriteLine("Invalid Number - The program will terminate\n");
                }
    
                for (int i = 0; i < 2; i++)
                {
                    for (int j = 0; j < 5; j++)
                    {
                        if (ItemID == ItemNumber[i, j])
                        {
                            Description = ItemName[i, j];
                            Price = UnitPrice[i, j];
                        }
                    }
                }
    
                Console.WriteLine("Receipt");
                Console.WriteLine("Item Number: {0}", ItemID);
                Console.WriteLine("Description: {0}", Description);
                Console.WriteLine("Unit Price:  {0:C}\n", Price);
    
                return 0;
            }
        }
    }
  2. Execute the application and test it. Here is an example:
     
    Enter Item Number: 739579
    Receipt
    Item Number: 739579
    Description: Men Cotton Polo Shirt
    Unit Price:  $45.55
    
    Press any key to continue . . .
  3. Close the DOW window
  4. Execute the application again and enter a different item number. Here is an example:
     
    Enter Item Number: 273644
    Receipt
    Item Number: 273644
    Description: Unknown
    Unit Price:  $0.00
    
    Press any key to continue . . .
  5. Close the DOS window
 

Previous Copyright © 2006 FunctionX, Inc. Next