Home

Techniques of Using Arrays

 

Main()'s Argument

 

Introduction

When a program starts, it looks for an entry point as the area of entrance. This is the role of the Main() function. In fact, a program, that is an executable program, starts by, and stops with, the Main() function. The way this works is that, at the beginning, the compiler enters he Main() function in a top-down approach, starting just after the opening curly bracket. If it finds a problem and judges that it is not worth continuing, it stops and lets you know. If, or as long as, it doesn't find a problem, it continues line after line, with the option to even call or execute a method in the same file or in another file. This process continues to the closing curly bracket "}". Once the compiler finds the closing bracket, the whole program has ended and stops.

If you want the user to provide additional information when executing your program, you can take care of this in the Main() function as this is the entry point of your program.

Practical Learning Practical Learning: Introducing the Command Line

  1. In Notepad, start a new empty file and type the following:
     
    using System;
    
    namespace CSharpLessons
    {
        class Exercise
        {
    	static int Main()
    	{
    	    string FirstName = "James";
         	    string LastName  = "Weinberg";
                 double WeeklyHours = 36.50;
    	    double HourlySalary = 12.58;
    	   
    	    string FullName = LastName + ", " + FirstName;
    	    double WeeklySalary = WeeklyHours * HourlySalary;
    
    	    Console.WriteLine("Employee Payroll");
    	    Console.WriteLine("Full Name:    {0}", FullName);
    Console.WriteLine("WeeklySalary: {0}", WeeklySalary.ToString("C"));
    
    	    return 0;
    	}
        }
    }
  2. Save the file in a new folder named CommandLine1
  3. Save the file itself as Exercise.cs in the CommandLine1 folder
  4. To test the application, open the Command Prompt and change to the folder in which you created the C# file
  5. Type csc Exercise.cs and press Enter
  6. To execute the program, type the name Exercise and press Enter. This would produce:
     
    C:\CSharp Lessons\CommandLine1>csc Exercise.cs
    Microsoft (R) Visual C# .NET Compiler version 7.10.3052.4
    for Microsoft (R) .NET Framework version 1.1.4322
    Copyright (C) Microsoft Corporation 2001-2002. All rights reserved.
    
    
    C:\CSharp Lessons\CommandLine1>Exercise
    Employee Payroll
    Full Name:    Weinberg, James
    WeeklySalary: $459.17
    
    C:\CSharp Lessons\CommandLine1>
  7. Return to your text editor
 

Command Request from Main()

So far, to compile a program, we simply typed the csc command at the command prompt. Then, to execute a program, we typed its name at the prompt. If we distributed one of these programs, we would tell the user to type the name of the program at the command prompt. In some cases, you may want the user to type additional information besides the name of the program. To request additional information from the user, pass a string argument to the Main() function. The argument should be passed as an array and make sure you provide a name for the argument. Here is an example:

using System;

class ObjectName
{
    static int Main(string[] args)
    {
        return 0;
    }
}

The reason you pass the argument as an array is so you can use as many values as you judge necessary. To provide values at the command prompt, the user types the name of the program followed by each necessary value. Here is an example:

The values the user would provide are stored in the zero-based argument array without considering the name of the program. The first value (that is, after the name of the program) is stored at index 0, the second at index 1, etc. Based on this, the first argument is represented by args[0], the second is represented by args[1], etc.

Since the array argument (like all C# arrays) is based on the Array class of the System namespace, if you want to find out how many values the user supplied, you can call the Array.Length property.

Each of the values the user types is a string. If any one of them is not a string, you should/must convert its string first to the appropriate value.

 

Practical Learning Practical Learning: Passing an Argument to Main()

  1. To pass an argument to Main(), change the file as follows:
     
    using System;
    
    namespace CSharpLessons
    {
        class Exercise
        {
    	static int Main(string[] Argument)
    	{
    	    string FirstName;
         	    string LastName;
                        Double WeeklyHours;
    	    Double HourlySalary;
    	   
    	    FirstName    = Argument[0];
                        LastName     = Argument[1];
    	    WeeklyHours  = Double.Parse(Argument[2]);
    	    HourlySalary = Double.Parse(Argument[3]);
    
    	    string FullName = LastName + ", " + FirstName;
    	    Double WeeklySalary = WeeklyHours * HourlySalary;
    
    	    Console.WriteLine("Employee Payroll");
    	    Console.WriteLine("Full Name:       {0}", FullName);
    Console.WriteLine("WeeklySalary: {0}", WeeklySalary.ToString("C"));
    
    	    return 0;
    	}
        }
    }
  2. Save the file and switch to the command prompt
  3. To compile the application, type csc Exercise.cs and press Enter
  4. To execute the program, type Exercise followed by a first name, a last name, and two decimal values. An example would be Exercise Catherine Engolo 42.50 20.48
     
  5. Return to your text editor

Two-Dimensional Arrays

 

Introduction

The arrays we used so far were made of a uniform series, where all members constituted 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. Start a new file in Notepad and type the following:
     
    using System;
    
    class DepartmentStore
    {
    	static int Main()
    	{
    		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;
    	}
    }
  2. Save the file in a new folder named DeptStore4
  3. Save the file as Exercise.cs
  4. Open the Command Prompt and change to the above DeptStore4
  5. Compile the exercise with csc Exercise.cs and execute it with Exercise
    This would produce:
     
    Receipt
    Item Number: 0
    Description: Unknown
    Unit Price:  $0.00
  6. Return to Notepad

Creation of 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;
    
    class DepartmentStore
    {
    	static int Main()
    	{
    		// 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 } };
    		
    		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;
    	}
    }
  2. Save the file

Access to 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;
    
    class DepartmentStore
    {
    	static int Main()
    	{
    		// 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 } };
    		
    		long    ItemID = 0;
    		string  Description = "Unknown";
    		decimal Price = 0.00M;
    
    		// 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. Save, compile, and execute the application. Here is an example:
     
    Enter Item Number: 397494
    Receipt
    Item Number: 397494
    Description: Unknown
    Unit Price:  $0.00
  3. Here is another example of executing the application:
     
    Enter Item Number: 367583
    Receipt
    Item Number: 367583
    Description:    Children Cable-knit Sweater
    Unit Price:       $25.65
  4. Return to Notepad

Multidimensional Arrays

 

Introduction

Beyond two dimensions, you can create a variable that represents various lists and each list contains various internal lists. This is referred to as a multidimensional array.

 

Creation of a Multidimensional Array

To create a mutidimensional array, add as many commas in the square brackets as you judge them necessary. Here is an example of a three-dimensional array initialized:

using System;

namespace CSharpLessons
{
    class Exercise
    {
	static void Main()
	{
	    double[,,] number = new double[2,3,5]{ { {  12.44, 525.38,  -6.28,  2448.32, 632.04},
                                                      {-378.05,  48.14, 634.18,   762.48,  83.02},
					        {  64.92,  -7.44,  86.74,  -534.60, 386.73} },
	                                              { {  48.02, 120.44,  38.62,   526.82,1704.62},
					        {  56.85, 105.48, 363.31,  172.62,  128.48},
					        {  906.68, 47.12,-166.07,  4444.26, 408.62} },
					     };
			
	   Console.WriteLine("Number of items {0}", number.Length);
                   Console.WriteLine("Number of items {0}", number.Rank);

                   Console.WriteLine();
	}
}

In this example, we are creating 2 groups of items. Each of the two groups is made of three lists. Each list contains 5 numbers. This would produce:

Number of items 30
Number of items 3

Access to Members of a Multidimensional Array

To locate each member of a multidimensional array, type the name of the array followed by the opening square bracket, followed by the 0-based first dimension, followed by a comma. Continue with each dimension and end with the closing square bracket. Here is an example:

using System;

namespace CSharpLessons
{
    class Exercise
    {
	static void Main()
	{
	    double[,,] number = new double[2,3,5]{ { {  12.44, 525.38,  -6.28,  2448.32, 632.04},
                                                      {-378.05,  48.14, 634.18,   762.48,  83.02},
					         {  64.92,  -7.44,  86.74,  -534.60, 386.73} },
	                                           { {  48.02, 120.44,  38.62,   526.82,1704.62},
					         {  56.85, 105.48, 363.31,  172.62,  128.48},
						{  906.68, 47.12,-166.07,  4444.26, 408.62} },
					       };
	
	    Console.WriteLine("Number[0][0][0] = {0}", number[0,0,0]);
	    Console.WriteLine("Number[0][0][1] = {0}", number[0,0,1]);
	    Console.WriteLine("Number[0][0][2] = {0}", number[0,0,2]);
	    Console.WriteLine("Number[0][0][3] = {0}", number[0,0,3]);
	    Console.WriteLine("Number[0][0][4] = {0}\n", number[0,0,4]);
			
	    Console.WriteLine("Number[0][1][0] = {0}", number[0,1,0]);
	    Console.WriteLine("Number[0][1][1] = {0}", number[0,1,1]);
	    Console.WriteLine("Number[0][1][2] = {0}", number[0,1,2]);
	    Console.WriteLine("Number[0][1][3] = {0}", number[0,1,3]);
             Console.WriteLine("Number[0][1][4] = {0}\n", number[0,1,4]);

	    Console.WriteLine("Number[0][2][0] = {0}", number[0,2,0]);
	    Console.WriteLine("Number[0][2][1] = {0}", number[0,2,1]);
	    Console.WriteLine("Number[0][2][2] = {0}", number[0,2,2]);
	    Console.WriteLine("Number[0][2][3] = {0}", number[0,2,3]);
             Console.WriteLine("Number[0][2][4] = {0}\n", number[0,2,4]);

	    Console.WriteLine("Number[1][0][0] = {0}", number[1,0,0]);
	    Console.WriteLine("Number[1][0][1] = {0}", number[1,0,1]);
	    Console.WriteLine("Number[1][0][2] = {0}", number[1,0,2]);
	    Console.WriteLine("Number[1][0][3] = {0}", number[1,0,3]);
	    Console.WriteLine("Number[1][0][4] = {0}\n", number[1,0,4]);
			
	    Console.WriteLine("Number[1][1][0] = {0}", number[1,1,0]);
	    Console.WriteLine("Number[1][1][1] = {0}", number[1,1,1]);
             Console.WriteLine("Number[1][1][2] = {0}", number[1,1,2]);
	    Console.WriteLine("Number[1][1][3] = {0}", number[1,1,3]);
             Console.WriteLine("Number[1][1][4] = {0}\n", number[1,1,4]);

	    Console.WriteLine("Number[1][2][0] = {0}", number[1,2,0]);
	    Console.WriteLine("Number[1][2][1] = {0}", number[1,2,1]);
	    Console.WriteLine("Number[1][2][2] = {0}", number[1,2,2]);
	    Console.WriteLine("Number[1][2][3] = {0}", number[1,2,3]);
             Console.WriteLine("Number[1][2][4] = {0}\n", number[1,2,4]);

	    Console.WriteLine("Number of items {0}", number.Length);
             Console.WriteLine("Number of items {0}", number.Rank);

             Console.WriteLine();
	}
}

This would produce:

Number[0][0][0] = 12.44
Number[0][0][1] = 525.38
Number[0][0][2] = -6.28
Number[0][0][3] = 2448.32
Number[0][0][4] = 632.04

Number[0][1][0] = -378.05
Number[0][1][1] = 48.14
Number[0][1][2] = 634.18
Number[0][1][3] = 762.48
Number[0][1][4] = 83.02

Number[0][2][0] = 64.92
Number[0][2][1] = -7.44
Number[0][2][2] = 86.74
Number[0][2][3] = -534.6
Number[0][2][4] = 386.73

Number[1][0][0] = 48.02
Number[1][0][1] = 120.44
Number[1][0][2] = 38.62
Number[1][0][3] = 526.82
Number[1][0][4] = 1704.62

Number[1][1][0] = 56.85
Number[1][1][1] = 105.48
Number[1][1][2] = 363.31
Number[1][1][3] = 172.62
Number[1][1][4] = 128.48

Number[1][2][0] = 906.68
Number[1][2][1] = 47.12
Number[1][2][2] = -166.07
Number[1][2][3] = 4444.26
Number[1][2][4] = 408.62

Number of items 30
Number of items 3

Jagged Arrays

 

Introduction

A jagged array is just an array of arrays, or an array of arrays of arrays, etc. To create a jagged array, use a combination of square brackets for each dimension. The formula used is:

DataType[][] VariableName;

Each of the square brackets is used in any of the ways we have introduced arrays so far. This means that the first square bracket can be used as its own one-dimensional array or as a multi-dimensional array. Here is an example:

long[2][5] Distances;

This declares a variable that represents two arrays and each array internally contains 5 arrays. The first square bracket can also be used as its own multidimensional array. Here is an example:

long[2,4][5] Distances;

In the same way, the second square bracket can be used as a single or a multidimensional array. Here is an example:

long[2,4][5,12,8] Distances;

Practical Learning Practical Learning: Introducing Jagged Arrays

  1. Start a new file in Notepad and type the following:
     
    using System;
    
    class DepartmentStore
    {
    	static int Main()
    	{
    		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;
    	}
    }
  2. Save the file in a new folder named DeptStore5
  3. Save the file as Exercise.cs
  4. Open the Command Prompt and change to the above DeptStore5
  5. Compile the exercise with csc Exercise.cs and execute it with Exercise
    This would produce:
     
    Receipt
    Item Number: 0
    Description: Unknown
    Unit Price:  $0.00
  6. Return to Notepad

Initialization of a Jagged Array

When declaring a jagged array, you can allocate memory for it using the new operator followed by the data type of the array and the same combination of square brackets used to the left of the assignment operator. The first square of the square brackets on the right side of the assignment operator must contain the external dimension of the array. The second pair of square brackets must be left empty. Here is an example:

using System;

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

		}
	}
}

To initialize a jagged array, when declaring the variable, on the right side of the second pair of square brackets, provide an opening and a closing curly brackets, then create each list in its own pair of curly brackets. At the beginning of each list, you must allocate memory for the list with the new operator. Here is an example:

using System;

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

			Console.WriteLine();
		}
	}
}

If you initialize the array this way, you can omit specifying the dimension of the external array. With a jagged array, you can also initialize its internal array individually. To do this, access each internal array by its zero-based index. Here is an example:

namespace CSharpLessons
{
	class Exercise
	{
		static void Main()
		{
			string[][] Members = new string[2][];
		
			Members[0] = new string[]{"Celeste", "Mathurin", "Alex", "Germain"};
			Members[1] = new string[]{"Jeremy", "Mathew", "Anselme", "Frederique"};

			Console.WriteLine();
		}
	}
}

Practical Learning Practical Learning: Initializing a Jagged Array

  1. To declare and initialize jagged arrays, change the file as follows:
     
    using System;
    
    class DepartmentStore
    {
    	static int Main()
    	{
    		// Each of the following variable arrays is structured as [2][2][4].
    		// Each variable represents:
    		// A/ Two major lists: The first major list represents women items,
    		//				       the second major list represents men items,
    		// B/ Two minor lists.
    		//    Each of the major lists contains two minor lists:
    		//	  a/ The first minor list of the first major list contains adult women items
    		//		 The second minor list of the first major list contains girls items
    		//	  b/ The first minor list of the second major list contains adult men items
    		//		 The second minor list of the second major list contains boys items
    		// C/ Each minor list contains four items
    
    		long[][][] ItemNumber = 
    			new long[][][]{
    				new long[][]{
    					new long[]{947783, 934687, 973947, 987598, 974937},
    					new long[]{743765, 747635, 765473, 754026, 730302}},
    			         new long[][]{
    					new long[]{209579, 267583, 248937, 276057, 267945},
    					new long[]{ 409579, 467583, 448937, 476057, 467945}} };
    		string[][][] ItemName =
    			new string[][][]{
    				new string[][]{
    					new string[]{ "Double-faced wool coat",
    					              "Floral Silk Tank Blouse",
    						     "Push Up Bra",
    						     "Chiffon Blouse",
    						     "Bow Belt Skirtsuit" },
    					new string[]{ "Cable-knit Sweater",
    					              "Jeans with Heart Belt",
    						     "Fashionable mini skirt",
    					              "Double Dry Pants",
                                                                "Romantic Flower Dress" } },
    				new string[][]{
    					new string[]{ "Cotton Polo Shirt",
    				                       "Pure Wool Cap",
                                                                "Striped Cotton Shirt",
                                                                "Two-Toned Ribbed Crewneck",
                                                                "Chestnut Italian Shoes" },
    					new string[]{ "Under Collar and Placket Jacket",
    		                                         "Country Coat Rugged Wear",
                                                                "Carpenter Jeans",
    		                                         "Double-Cushion Tennis Shoes",
                                                               "Stitched Center-Bar Belt" }} };
    		decimal[][][] UnitPrice =
    			new decimal[2][][]{
    				new decimal[][]{
    					new decimal[]{ 275.25M, 180.00M, 50.00M, 265.00M, 245.55M },
    					new decimal[]{ 45.55M, 25.65M, 34.55M, 28.55M, 24.95M }},
    				new decimal[][]{
    					new decimal[]{ 45.75M, 25.00M, 65.55M, 9.75M, 165.75M },
    					new decimal[]{ 265.15M, 35.55M, 24.95M, 48.75M, 32.50M }} };
    
    		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;
    	}
    }
  2. Save the file

Access to Members of a Jagged Array

As done for a multidimensional array, each member of a jagged array can be access with a multiple index, depending on how the array was created. Both the external and the internal lists are zero-based. Here is an example:

using System;

namespace CSharpLessons
{
    class Exercise
    {
	static void Main()
	{
	    string[][] Members = new string[2][];
		
	    Members[0] = new string[]{"Celeste", "Mathurin", "Alex", "Germain"};
	    Members[1] = new string[]{"Jeremy", "Mathew", "Anselme", "Frederique"};

	    Console.WriteLine("Member 1: {0}", Members[0][0]);
	    Console.WriteLine("Member 2: {0}", Members[0][1]);
	    Console.WriteLine("Member 3: {0}", Members[0][2]);
	    Console.WriteLine("Member 4: {0}", Members[0][3]);
	    Console.WriteLine("Member 5: {0}", Members[1][0]);
	    Console.WriteLine("Member 6: {0}", Members[1][1]);
	    Console.WriteLine("Member 7: {0}", Members[1][2]);
	    Console.WriteLine("Member 8: {0}\n", Members[1][3]);
	}
    }
}

This would produce:

Member 1: Celeste
Member 2: Mathurin
Member 3: Alex
Member 4: Germain
Member 5: Jeremy
Member 6: Mathew
Member 7: Anselme
Member 8: Frederique

Press any key to continue . . .

Practical Learning Practical Learning: Using a Jagged Array

  1. To process the members of a jagged array, make the following changes to the file:
     
    using System;
    
    class DepartmentStore
    {
    	static int Main()
    	{
    		// Each of the following variable arrays is structured as [2][2][4].
    		// Each variable represents:
    		// A/ Two major lists: The first major list represents women items,
    		//		  the second major list represents men items,
    		// B/ Two minor lists.
    		//     Each of the major lists contains two minor lists:
    		//     a/ The first minor list of the first major list contains adult women items
    		//         The second minor list of the first major list contains girls items
    		//     b/ The first minor list of the second major list contains adult men items
    		//         The second minor list of the second major list contains boys items
    		// C/ Each minor list contains four items
    
    		long[][][] ItemNumber = 
    			new long[][][]{
    				new long[][]{
    					new long[]{947783, 934687, 973947, 987598, 974937},
    					new long[]{743765, 747635, 765473, 754026, 730302}},
    			                new long[][]{
    					new long[]{209579, 267583, 248937, 276057, 267945},
    					new long[]{ 409579, 467583, 448937, 476057, 467945}} };
    		string[][][] ItemName =
    			new string[][][]{
    				new string[][]{
    					new string[]{ "Double-faced wool coat",
    					                      "Floral Silk Tank Blouse",
    						      "Push Up Bra",
    						      "Chiffon Blouse",
    						      "Bow Belt Skirtsuit" },
    					new string[]{  "Cable-knit Sweater",
    					               "Jeans with Heart Belt",
    						      "Fashionable mini skirt",
    					               "Double Dry Pants",
                                                                 "Romantic Flower Dress" } },
    				new string[][]{
    					new string[]{ "Cotton Polo Shirt",
    				                       "Pure Wool Cap",
                                                                "Striped Cotton Shirt",
                                                                "Two-Toned Ribbed Crewneck",
                                                                "Chestnut Italian Shoes" },
    					new string[]{ "Under Collar and Placket Jacket",
    		                                          "Country Coat Rugged Wear",
                                                                "Carpenter Jeans",
    		                                          "Double-Cushion Tennis Shoes",
                                                                "Stitched Center-Bar Belt" }} };
    		decimal[][][] UnitPrice =
    			new decimal[2][][]{
    				new decimal[][]{
    					new decimal[]{ 275.25M, 180.00M, 50.00M, 265.00M, 245.55M },
    					new decimal[]{ 45.55M, 25.65M, 34.55M, 28.55M, 24.95M }},
    				new decimal[][]{
    					new decimal[]{ 45.75M, 25.00M, 65.55M, 9.75M, 165.75M },
    					new decimal[]{ 265.15M, 35.55M, 24.95M, 48.75M, 32.50M }} };
    
    		long    ItemID = 0;
    		string  Description = "Unknown";
    		decimal Price = 0.00M;
    		string Category = "Category";
    
    		// 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 < 2; j++)
    			{
    				for(int k = 0; k < 5; k++)
    				{
    					if( ItemID == ItemNumber[i][j][k] )
    					{
    						Description = ItemName[i][j][k];
    						Price = UnitPrice[i][j][k];
    
    						if( ItemID >= 900000 )
    							Category = "Women";
    						else if( ItemID >= 700000 )
    							Category = "Girls";
    						else if( ItemID >= 400000 )
    							Category = "Boys";
    						else
    							Category = "Men";
    					}
    				}
    			}
    		}
    
    		Console.WriteLine("Receipt");
    		Console.WriteLine("Item Number: {0}", ItemID);
    		Console.WriteLine("Description: {0} - {1}", Category, Description);
    		Console.WriteLine("Unit Price:  {0:C}\n", Price);
    
    		return 0;
    	}
    }
  2. Save, compile, and execute the file

The .NET Framework Support of Arrays

 

Introduction

The techniques we have used to create arrays so far are part of the traditional routines used in many languages. The Microsoft .NET Framework goes further than that. Every time you declare an array, it inherits from a class called Array. The Array class provides support for any array using various properties and methods. After creating an array as we have done so far, you may want to rearrange the list based on one of the items. You may want to look for a particular item to find if it exists; then, if it exists, where it is located. The Array class provides many other routines to perform such operations.

 

Item Addition

As done so far, to add an item to a list, you specify its index and assign the desired value. Here is an example:

class Exercise
{
    static void Main()
    {
	string[] EmployeeName = new string[4];

	EmployeeName[0] = "Joan Fuller";
	EmployeeName[1] = "Barbara Boxen";
	EmployeeName[2] = "Paul Kumar";
	EmployeeName[3] = "Bertrand Entire";
    }
}

Alternatively, you can use the SetValue() method to add a new item to the list. This method has 8 versions. The first argument is the value that needs to be added to the list, the other argument(s) is(are) used for the index. Here is an example:

class Exercise
{
    static void Main()
    {
	string[] EmployeeName = new string[4];

	EmployeeName.SetValue("Joan Fuller", 0);
	EmployeeName.SetValue("Barbara Boxen", 1);
	EmployeeName.SetValue("Paul Kumar", 2);
	EmployeeName.SetValue("Bertrand Entire", 3);
    }
}
 

Item Retrieval

To locate an item of an array, we were using its index. Here is an example:

class Exercise
{
    static void Main()
    {
	string[] EmployeeName = new string[4];

	EmployeeName[0] = "Joan Fuller";
	EmployeeName[1] = "Barbara Boxen";
	EmployeeName[2] = "Paul Kouma";
	EmployeeName[3] = "Bertand Entire";

	Console.WriteLine("Employees Records");
	Console.WriteLine("Employee 1: {0}", EmployeeName[0]);
	Console.WriteLine("Employee 2: {0}", EmployeeName[1]);
	Console.WriteLine("Employee 3: {0}", EmployeeName[2]);
	Console.WriteLine("Employee 4: {0}", EmployeeName[3]);
    }
}

Alternatively, the Array class provides the GetValue() method, also loaded with 8 versions. Here is an example:

class Exercise
{
    static void Main()
    {
	string[] EmployeeName = new string[4];

	EmployeeName.SetValue("Joan Fuller", 0);
	EmployeeName.SetValue("Barbara Boxen", 1);
	EmployeeName.SetValue("Paul Kumar", 2);
	EmployeeName.SetValue("Bertrand Entire", 3);

	Console.WriteLine("Employees Records");
	Console.WriteLine("Employee 1: {0}", EmployeeName.GetValue(0));
	Console.WriteLine("Employee 2: {0}", EmployeeName.GetValue(1));
	Console.WriteLine("Employee 3: {0}", EmployeeName.GetValue(2));
	Console.WriteLine("Employee 4: {0}", EmployeeName.GetValue(3));
    }
}

 

The Length of an Array

Once an array has been created, you can use it as you see fit. We saw that, when creating an array, you can specify the number of its members, and you must do this if you are not initializing the array. As we saw already, if you are initializing an array when creating it, you don't have to specify its dimension. Here is an example:

using System;

namespace CSharpLessons
{
    class Exercise
    {
	static void Main()
	{
	    double[] number = new double[]{ 12.44, 525.38, 6.28, 2448.32, 632.04,
			                           -378, 48, 6348, 762, 83, 64, -7, 86,
				            534, -6, 386, 73, 5, -284, 3654, 671, 34, 693};

                    Console.WriteLine();
	}
}

Some time in your program, you may want to know how many members are in this type of array. You could get dizzy trying to count them and you may make a mistake with the count. All of the arrays used in C# derive from a class called Array. This class provides a property called Length. To find out how many members an array has, you can access its Length property. Here is an example:

using System;

namespace CSharpLessons
{
    class Exercise
    {
	static void Main()
	{
	    double[] number = new double[]{ 12.44, 525.38, 6.28, 2448.32, 632.04,
			                           -378, 48, 6348, 762, 83, 64, -7, 86,
				           534, -6, 386, 73, 5, -284, 3654, 671, 34, 693};
			
                    Console.WriteLine("Number of items {0}", number.Length);

                    Console.WriteLine();
	}
}

This would produce:

Number of items 23

The Dimensions of an Array

We have seen that the square brackets are used to specify to the compiler that you are declaring an array. If you are creating a one-dimensional array, we saw that you can type a number in the square bracket. If you are creating a two-dimensional array, you type two numbers separated by a comma in the second pair of square brackets. Each number, whether it is one, two, or more is a place holder for what is referred to a dimension. In other words, a one dimensional array has a dimension of one. A two-dimensional array has a dimension of 2.

To find out the dimension of an array, the Array class, which is the parent of all arrays, provides the Rank property. Therefore, to know the dimension of an existing array, you can access its Rank.

 

The Bounds of an Array

To better manage an array, the compiler must always be able to locate its highest and its lowest members. This is particularly important because an array must have a fixed size (by the way, using some gymnastic, an array can grow or shrink, a feature that is not available in C/C++ but can be managed in C# using the .NET Framework).

The lowest member of an array can be located using the Array.GetLowerBound() method. Its syntax is:

public int GetLowerBound(int dimension);

The highest member of an array can be located using the Array.GetUpperBound() method. Its syntax is:

public int GetUpperBound(int dimension);

In both cases, the dimension argument is the rank of the array. For a single-dimensional array, as those we have always used so far, this parameter must have the value of 0;

 

Previous Copyright 2004-2006 FunctionX, Inc. Next