Home

Introduction to Arrays

 

A Series of Similar Items

 

Introduction

Imagine you want to create a program that would use a series of numbers. In math, we represent such a series as follows: X1, X2, X3, X4, X5. You can also represent a list of items as follows:

Alex
Gaston
Hermine
Jerry

In C#, so far, to use a series of items, we were declaring a variable for each of them. If the list was made of numbers, we would declare variables for such numbers as follows:

using System;

namespace CSharpLessons
{
    class Exercise
    {
	static void Main()
	{
	    double number1 = 12.44,
	           number2 = 525.38,
		number3 = 6.28,
		number4 = 2448.32,
	                number5 = 632.04;
	}
    }
}

Instead of using individual variables that share the same characteristics, you can group them in an entity like a regular variable but called an array. Therefore, an array is a series of items of the same kind. It could be a group of numbers, a group of cars, a group of words, etc but all items of the array must be of the same type.

 

Practical LearningPractical Learning: Introducing Arrays

  1. Start Notepad
  2. In the empty file, type the following:
     
    using System;
    
    class IceCream
    {
    	public const decimal BasePrice     = 1.55M;
    	
    	public void ProcessAnOrder()
    	{
    		int dFlv   = 0,
    			dCont  = 0,
    			dIngrd = 0;
    		int Scoops;
    		decimal PriceIngredient, TotalPrice;
    
    		Console.WriteLine("Ice Cream Vendor Machine");
    
    		do 
    		{
    			try 
    			{
    				Console.WriteLine("What type of flavor do you want?");
    				Console.WriteLine("1 - ");
    				Console.WriteLine("2 - ");
    				Console.WriteLine("3 - ");
    				Console.WriteLine("4 - ");
    				Console.WriteLine("5 - ");
    				Console.WriteLine("6 - ");
    				Console.Write("Your Choice? " );
    				dFlv = int.Parse(Console.ReadLine());
    			}
    			catch(FormatException)
    			{
    				Console.WriteLine("You must enter a valid number and no other character!");
    			}
    				
    			if( dFlv < 1 || dFlv > 6 )
    				Console.WriteLine("Invalid Choice - Try Again!\n");
    		} while( dFlv < 1 || dFlv > 6 );
    
    		do 
    		{
    			try 
    			{
    				Console.WriteLine("What type of container do you want?");
    				Console.WriteLine("1 - ");
    				Console.WriteLine("2 - ");
    				Console.WriteLine("3 - ");
    				Console.Write("Your Choice? ");
    				dCont = int.Parse(Console.ReadLine());
    			}
    			catch(FormatException)
    			{
    				Console.WriteLine("You must enter a valid number and no other character!");
    			}
    				
    			if( dCont < 1 || dCont > 3 )
    				Console.WriteLine("Invalid Choice - Try Again!");
    		} while( dCont < 1 || dCont > 3 );
    
    		do 
    		{
    			try 
    			{
    				Console.WriteLine("Do you want an ingredient or not");
    				Console.WriteLine("1 - ");
    				Console.WriteLine("2 - ");
    				Console.WriteLine("3 - ");
    				Console.WriteLine("4 - ");
    				Console.Write("Your Choice? ");
    				dIngrd = int.Parse(Console.ReadLine());
    			}
    			catch(FormatException)
    			{
    				Console.WriteLine("You must enter a valid number and no other character!");
    			}
    
    			if( dIngrd < 1 || dIngrd > 4 )
    				Console.WriteLine("Invalid Choice - Try Again!");
    		} while( dIngrd < 1 || dIngrd > 4 );
    
    		do
    		{
    			try 
    			{
    				Console.Write("How many scoops(1, 2, or 3)? ");
    				Scoops = int.Parse(Console.ReadLine());
    			}
    			catch(FormatException)
    			{
    				Console.WriteLine("You must enter a valid number and no other character!");
    			}
    
    			if( Scoops < 1 || Scoops > 3 )
    				Console.WriteLine("Invalid Choice - Try Again!");
    		} while( Scoops < 1 || Scoops > 3 );
    
    		if( dIngrd == 2 || dIngrd == 3 || dIngrd == 4 )
    			PriceIngredient = 0.65M;
    		else
    			PriceIngredient = 0.00M;
    
    		TotalPrice = (BasePrice * Scoops) + PriceIngredient;
    
    		DisplayReceipt(dFlv, dCont, dIngrd, Scoops, TotalPrice);
    	}
    
    	public void DisplayReceipt(int Flv, int Cont, int Ingrd,
    		                       int spoons, decimal TotalPrice)
    	{
    		Console.WriteLine("\nIce Cream Order");
    
    		Console.WriteLine("Scoops:      {0}",   spoons);
    		Console.WriteLine("Total Price: {0:C}\n", TotalPrice);
    	}
    }
  3. Save the file in a new folder named IceCream2
  4. Save the file itself as Order.cs in the IceSream2 folder
  5. Start another instance of Notepad and type the following:
     
    using System;
    
    class Exercise
    {
        static void Main()
        {
        }
    }
  6. Save the file as Exercise.cs in the IceCream2 folder

Array Creation

Before creating an array, you must first decide the type its items will be made of. Is it a group of numbers, a group of chairs, a group of buttons on a remote controls? This information allows the compiler to know how much space each item of the group will require. This is because each item of the group will occupy its own memory space, just like any of the variables we have used so far.

After deciding about the type of data of the items that make up the series, you must use a common name to identify them. The name is simply the same type you would use for a variable as we have used so far. The name allows you and the compiler to identify the area in memory where the items are located.

Thirdly, you must specify the number of items that will constitute the group. For the compiler to be able to allocate an adequate amount of space for the items of the list, once it knows how much space each item will require, it needs to know the number of items so an appropriate and large enough amount of space can be reserved. The number of items of an array is included in square brackets, as in [5].

In C# (unlike some other languages like C/C++ or Pascal), an array is considered a reference type. Therefore, an array requests its memory using the new operator (like a pointer in C/C++). Based on this, the basic formula to declare an array is:

DataType[] VariableName = new DataType[Number];

In this formula, the DataType factor can be one of the types we have used so far. It can also be the name of a class. The square brackets on the left of the assignment operator are used to let the compiler know that you are declaring an array instead of a regular variable. The new operator allows the compiler to reserve memory in the heap. The Number factor is used to specify the number of items of the list.

Based on the above formula, here is an example of an array variable:

using System;

namespace CSharpLessons
{
    class Exercise
    {
	static void Main()
	{
	    double[] number = new double[5];

                    Console.WriteLine();
	}
    }
}
 

Practical LearningPractical Learning: Creating an Array

  1. To create arrays, access the Order.cs file and change it as follows:
     
    using System;
    
    class IceCream
    {
    	public const decimal BasePrice     = 1.55M;
    	
    	public void ProcessAnOrder()
    	{
    		int dFlv   = 0,
    		    dCont  = 0,
    		    dIngrd = 0;
    		int Scoops = 0;
    		decimal PriceIngredient, TotalPrice;
    		
    		string[] Flavor = new string[6]; 
    		string[] Container = new string[3];
    		string[] Ingredient = new string[4];
    
    		Console.WriteLine("Ice Cream Vendor Machine");
    
    		. . . No Change
    		
    	}
    
    	. . . No Change
    }
  2. Save the file

Operations on Arrays

 

Array Initialization

When creating an array, you can specify the number of items that make up its list. Each item of the series is referred to as a member of the array. Once the array has been created, each one of its members is initialized with a 0 value. Most, if not all, of the time, you will need to change the value of each member to a value of your choice. This is referred to as initializing the array.

An array is primarily a variable; it is simply meant to carry more than one value. Like every other variable, an array can be initialized. There are two main techniques you can use to initialize an array. If you have declared an array as done above, to initialize it, you can access each one of its members and assign it a desired but appropriate value.

In math, if you create a series of values as X1, X2, X3, X4, and X5, each member of this series can be identified by its subscript number. In this case the subscripts are 1, 2, 3, 4, and 5. This subscript number is also called an index. In the case of an array also, each member of an array can be referred to by an incremental number called an index. A C# (like a C/C++) array is zero-based. This means that the first member of the series has an index of 0, the second has an index of 1. In math, the series would be represented as X0, X1, X2, X3, and X4. In C#, the index of a member of an array is written in its own square brackets. This is the notation you would use to locate each member. One of the actions you can take would consist of assigning it a value. Here is an example:

using System;

namespace CSharpLessons
{
    class Exercise
    {
	static void Main()
	{
	    double[] number = new double[5];

             number[0] = 12.44;
             number[1] = 525.38;
	    number[2] = 6.28;
             number[3] = 2448.32;
             number[4] = 632.04;

             Console.WriteLine();
	}
    }
}

Besides this technique, you can also initialize the array as a whole when declaring it. To do this, on the right side of the declaration, before the closing semi-colon, type the values of the array members between curly brackets and separated by a comma. Here is an example:

using System;

namespace CSharpLessons
{
    class Exercise
    {
	static void Main()
	{
	 double[] number = new double[5]{ 12.44, 525.38, 6.28, 2448.32, 632.04 };

            	    Console.WriteLine();
	}
    }
}

If you use this second technique, you don't have to specify the number of items in the series. If you can leave all square brackets empty:

 
using System;

namespace CSharpLessons
{
	class Exercise
	{
		static void Main()
		{
			double[] number = new double[]{ 12.44, 525.38, 6.28, 2448.32, 632.04 };

			Console.WriteLine();
		}
	}
}

If you leave the square brackets empty, the compiler will figure out the number of items.

Practical LearningPractical Learning: Using the Members of an Array

  1. To initialize arrays and use their members, change the Order.cs file as follows:
     
    using System;
    
    class IceCream
    {
    	public const decimal BasePrice     = 1.55M;
    	
    	public void ProcessAnOrder()
    	{
    		int dFlv     = 0,
    		     dCont  = 0,
    		     dIngrd = 0;
    		int Scoops = 0;
    		decimal PriceIngredient, TotalPrice;
    		
    		string[] Flavor = new string[6]{ "Vanilla",
    				               "Cream of Cocoa",
    					      "Organic Strawberry",
    					      "Butter Pecan",
    					      "Cherry Coke",
    					      "Chocolate Brownies" };
    		
    		string[] Container = new string[3];
    		Container[0] = "Cone";
    		Container[1] = "Cup";
    		Container[2] = "Bowl";
    
    		string[] Ingredient = new string[]{"No Ingredient",
    					        "Peanuts",
    				                 "M & M",
    	                                             "Cookies" };
    
    		Console.WriteLine("Ice Cream Vendor Machine");
    
    		do 
    		{
    			try 
    			{
    				Console.WriteLine("What type of flavor do you want?");
    				Console.WriteLine("1 - {0}", Flavor[0]);
    				Console.WriteLine("2 - {0}", Flavor[1]);
    				Console.WriteLine("3 - {0}", Flavor[2]);
    				Console.WriteLine("4 - {0}", Flavor[3]);
    				Console.WriteLine("5 - {0}", Flavor[4]);
    				Console.WriteLine("6 - {0}", Flavor[5]);
    				Console.Write("Your Choice? " );
    				dFlv = int.Parse(Console.ReadLine());
    			}
    			catch(FormatException)
    			{
    				Console.WriteLine("You must enter a valid number and no other character!");
    			}
    				
    			if( dFlv < 1 || dFlv > 6 )
    				Console.WriteLine("Invalid Choice - Try Again!\n");
    		} while( dFlv < 1 || dFlv > 6 );
    
    		do 
    		{
    			try 
    			{
    				Console.WriteLine("What type of container do you want?");
    				Console.WriteLine("1 - {0}", Container[0]);
    				Console.WriteLine("2 - {0}", Container[1]);
    				Console.WriteLine("3 - {0}", Container[2]);
    				Console.Write("Your Choice? ");
    				dCont = int.Parse(Console.ReadLine());
    			}
    			catch(FormatException)
    			{
    				Console.WriteLine("You must enter a valid number and no other character!");
    			}
    				
    			if( dCont < 1 || dCont > 3 )
    				Console.WriteLine("Invalid Choice - Try Again!");
    		} while( dCont < 1 || dCont > 3 );
    
    		do 
    		{
    			try 
    			{
    				Console.WriteLine("Do you want an ingredient or not");
    				Console.WriteLine("1 - {0}", Ingredient[0]);
    				Console.WriteLine("2 - {0}", Ingredient[1]);
    				Console.WriteLine("3 - {0}", Ingredient[2]);
    				Console.WriteLine("4 - {0}", Ingredient[3]);
    				Console.Write("Your Choice? ");
    				dIngrd = int.Parse(Console.ReadLine());
    			}
    			catch(FormatException)
    			{
    				Console.WriteLine("You must enter a valid number and no other character!");
    			}
    
    			if( dIngrd < 1 || dIngrd > 4 )
    				Console.WriteLine("Invalid Choice - Try Again!");
    		} while( dIngrd < 1 || dIngrd > 4 );
    
    		do
    		{
    			try 
    			{
    				Console.Write("How many scoops(1, 2, or 3)? ");
    				Scoops = int.Parse(Console.ReadLine());
    			}
    			catch(FormatException)
    			{
    		Console.WriteLine("You must enter a valid number and no other character!");
    			}
    
    			if( Scoops < 1 || Scoops > 3 )
    				Console.WriteLine("Invalid Choice - Try Again!");
    		} while( Scoops < 1 || Scoops > 3 );
    
    		if( dIngrd == 2 || dIngrd == 3 || dIngrd == 4 )
    			PriceIngredient = 0.65M;
    		else
    			PriceIngredient = 0.00M;
    
    		TotalPrice = (BasePrice * Scoops) + PriceIngredient;
    
    		DisplayReceipt(dFlv, dCont, dIngrd, Scoops, TotalPrice);
    	}
    
    	public void DisplayReceipt(int Flv, int Cont, int Ingrd,
    		int spoons, decimal TotalPrice)
    	{
    		Console.WriteLine("\nIce Cream Order");
    		switch(Flv)
    		{
    			case 2:
    				Console.WriteLine("Flavor:      Cream of Cocoa");
    				break;
    			case 3:
    				Console.WriteLine("Flavor:      Organic Strawberry");
    				break;
    			case 4:
    				Console.WriteLine("Flavor:      Butter Pecan");
    				break;
    			case 5:
    				Console.WriteLine("Flavor:      Cherry Coke");
    				break;
    			case 6:
    				Console.WriteLine("Flavor:      Chocolate Brownies");
    				break;
    			default:
    				Console.WriteLine("Flavor:      Vavilla");
    				break;
    		}
    	
    		switch(Cont)
    		{
    			case 2:
    				Console.WriteLine("Container:   Cup");
    				break;
    			case 3:
    				Console.WriteLine("Container:   Bowl");
    				break;
    			default:
    				Console.WriteLine("Container:   Cone");
    				break;
    		}
    		
    		switch(Ingrd)
    		{
    			case 2:
    				Console.WriteLine("Ingredient:  Peanuts");
    				break;
    			case 3:
    				Console.WriteLine("Ingredient:  M & M");
    				break;
    			case 4:
    				Console.WriteLine("Ingredient:  Cookies");
    				break;
    			default:
    				Console.WriteLine("Ingredient:  None");
    				break;
    		}
    
    		Console.WriteLine("Scoops:      {0}",   spoons);
    		Console.WriteLine("Total Price: {0:C}\n", TotalPrice);
    	}
    }
  2. Save the Order.cs file
  3. To test the IceCream class, access the Exercise.cs file and change it as follows:
     
    using System;
    
    class Exercise
    {
    	static void Main()
    	{
    		IceCream IS = new IceCream();
    
    		IS.ProcessAnOrder();
    	}
    }
  4. Save the Exercise.cs file
  5. To test the application, open the Command Prompt and change to the folder in which you created the C# file
  6. Type csc Order.cs Exercise.cs and press Enter
  7. After compiling, type Exercise to execute and press Enter. Here is an example:
     
    Ice Cream Vendor Machine
    What type of flavor do you want?
    1 - Vanilla
    2 - Cream of Cocoa
    3 - Organic Strawberry
    4 - Butter Pecan
    5 - Cherry Coke
    6 - Chocolate Brownies
    Your Choice? 8
    Invalid Choice - Try Again!
    
    What type of flavor do you want?
    1 - Vanilla
    2 - Cream of Cocoa
    3 - Organic Strawberry
    4 - Butter Pecan
    5 - Cherry Coke
    6 - Chocolate Brownies
    Your Choice? 2
    What type of container do you want?
    1 - Cone
    2 - Cup
    3 - Bowl
    Your Choice? w
    You must enter a valid number and no other character!
    Invalid Choice - Try Again!
    What type of container do you want?
    1 - Cone
    2 - Cup
    3 - Bowl
    Your Choice? 2
    Do you want an ingredient or not
    1 - No Ingredient
    2 - Peanuts
    3 - M & M
    4 - Cookies
    Your Choice? p
    You must enter a valid number and no other character!
    Invalid Choice - Try Again!
    Do you want an ingredient or not
    1 - No Ingredient
    2 - Peanuts
    3 - M & M
    4 - Cookies
    Your Choice? 2
    How many scoops(1, 2, or 3)? 2
    
    Ice Cream Order
    Flavor:      Cream of Cocoa
    Container:   Cup
    Ingredient:  Peanuts
    Scoops:      2
    Total Price: $3.75
  8. Return to Notepad
 

Arrays and Methods

 

A Member of an Array as Parameter

Each member of an array is considered a sub-variable; that is, a variable in its own right with a value. Based on this, you can pass a single member of an array as argument. In this case, you can pass the name of the array variable with the accompanying index to a method. The parameter transmitted to the method is passed by value.

 

Practical LearningPractical Learning: Passing a Member of an Array as Argument

  1. To pass members of array to a method, access the Order.cs file and change it as follows:
     
    using System;
    
    class IceCream
    {
    	public const decimal BasePrice     = 1.55M;
    	public const string  DefaultFlavor = "Diet Mint Fudge High Carb";
    
    	public void ProcessAnOrder()
    	{
    		. . . No Change 			
    		
    
    		TotalPrice = BasePrice + PriceScoop + PriceIngredient;
    
    		DisplayReceipt(Flavor[dFlv-1], Container[dCont-1],
    			     Ingredient[dIngrd-1], Scoops, TotalPrice);
    	}
    
    public void DisplayReceipt(string Flv, string Cont, string Ingrd,
    		int spoons, decimal TotalPrice)
    	{
    		Console.WriteLine("\nIce Cream Order");
    		Console.WriteLine("Flavor:      {0}", Flv);
    		Console.WriteLine("Container:   {0}", Cont);
    		Console.WriteLine("Ingredient:  {0}", Ingrd);
    		Console.WriteLine("Scoops:      {0}",   spoons);
    		Console.WriteLine("Total Price: {0:C}\n", TotalPrice);
    	}
    }
  2. Save the file
  3. Compile the exercise with csc Order.cs Exercise.cs
  4. Execute it with Exercise

An Array Passed as Argument

The main purpose of using an array is to use various pseudo-variables grouped under one name. Still, an array is primarily a variable. As such, it can be passed to a method and it can be returned from a method. Like a regular variable, an array can be passed as argument. To do this, in the parentheses of a method, provide the data type, the empty square brackets, and the name of the argument. Here is an example:

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
        }

        static void DisplayNumber(Double[] n)
        {
        }
    }
}

When an array has been passed to a method, it can be used in the body of the method as an array can be, following the rules of array variables. For example, you can display its values. Because an array is derived from the Array class of the System namespace, an array passed as argument carries its number of members. This means that you don't have to pass an additional argument, as done in C++.

The simplest way you can use an array is to display the values of its members. This could be done as follows:

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
        }

        static void DisplayNumber(Double[] n)
        {
            for (int i = 0; i < 5; i++)
                Console.WriteLine("Number {0}: {1}", i, n[i]);
        }
    }
}

To call a method that takes an array as argument, simply type the name of the array in the parentheses of the called method. Here is an example:

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            Double[] number = new Double[5];

            number[0] = 12.44;
            number[1] = 525.38;
            number[2] = 6.28;
            number[3] = 2448.32;
            number[4] = 632.04;

            DisplayNumber(number);
        }

        static void DisplayNumber(Double[] n)
        {
            for (int i = 0; i < 5; i++)
                Console.WriteLine("Number {0}: {1}", i, n[i]);
        }
    }
}

This would produce:

Number 0: 12.44
Number 1: 525.38
Number 2: 6.28
Number 3: 2448.32
Number 4: 632.04

When an array is passed as argument to a method, the array is passed by reference. This means that, if the method makes any change to the array, the change would be kept when the method exits. You can use this characteristic to initialize an array from a method. Here is an example:

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            Double[] number = new Double[5];

            InitializeList(number);
            DisplayNumber(number);
        }

        static void InitializeList(Double[] nbr)
        {
            nbr[0] = 12.44;
            nbr[1] = 525.38;
            nbr[2] = 6.28;
            nbr[3] = 2448.32;
            nbr[4] = 632.04;
        }

        static void DisplayNumber(Double[] n)
        {
            for (int i = 0; i < 5; i++)
                Console.WriteLine("Number {0}: {1}", i, n[i]);
        }
    }
}

Notice that the InitializeList() method receives an un-initialized array but returns it with new values.

To enforce the concept of passing a variable by reference, you can also accompany an array argument with the ref keyword, both when defining the method and when calling it. Here is an example:

using System;

namespace ConsoleApplication1
{
    class Program
    {

        static void Main()
        {
            Double[] number = new Double[5];

            InitializeList(ref number);
            DisplayNumber(ref number);
        }
        static void InitializeList(ref Double[] nbr)
        {
            nbr[0] = 12.44;
            nbr[1] = 525.38;
            nbr[2] = 6.28;
            nbr[3] = 2448.32;
            nbr[4] = 632.04;
        }

        static void DisplayNumber(ref Double[] n)
        {
            for (int i = 0; i < 5; i++)
                Console.WriteLine("Number {0}: {1}", i, n[i]);
        }
    }
}

Practical LearningPractical Learning: Passing an Array as Argument

  1. To use examples of passing arrays to methods, change the Order.cs file as follows:
     
    using System;
    
    class IceCream
    {
    	public const decimal BasePrice     = 1.55M;
    	
    	private void PrepareFlavors(string[] Flavors)
    	{
    		Flavors[0] = "Vanilla";
    		Flavors[1] = "Cream of Cocoa";
    		Flavors[2] = "Organic Strawberry";
    		Flavors[3] = "Butter Pecan";
    		Flavors[4] = "Cherry Coke";
    		Flavors[5] = "Chocolate Brownies";
    	}
    
    	private void CreateIngredients(string[] Ingredients)
    	{
    		Ingredients[0] = "No Ingredient";
    		Ingredients[1] = "Peanuts";
    		Ingredients[2] = "M & M";
    		Ingredients[3] = "Cookies";
    	}
    
    	private int ChooseContainer(string[] Containers)
    	{
    		int choice = 1;
    
    		do 
    		{
    			try 
    			{
    				Console.WriteLine("What type of container do you want?");
    				for(int i = 0; i < 3; i++)
    					Console.WriteLine("{0} - {1}", i+1, Containers[i]);
    				Console.Write("Your Choice? ");
    				choice = int.Parse(Console.ReadLine());
    			}
    			catch(FormatException)
    			{
    				Console.WriteLine("You must enter a valid number and no other character!");
    			}
    				
    			if( choice < 1 || choice > 3 )
    				Console.WriteLine("Invalid Choice - Try Again!");
    		} while( choice < 1 || choice > 3 );
    
    		return choice;
    	}
    
    	private int RequestFlavor(string[] Flavors)
    	{
    		int choice = 1;
    
    		do 
    		{
    			try 
    			{
    				Console.WriteLine("What type of flavor do you want?");
    				for(int i = 0; i < 6; i++)
    					Console.WriteLine("{0} - {1}", i+1, Flavors[i]);
    				Console.Write("Your Choice? " );
    				choice = int.Parse(Console.ReadLine());
    			}
    			catch(FormatException)
    			{
    				Console.WriteLine("You must enter a valid number and no other character!");
    			}
    				
    			if( choice < 1 || choice > 6 )
    				Console.WriteLine("Invalid Choice - Try Again!\n");
    		} while( choice < 1 || choice > 6 );
    
    		return choice;
    	}
    
    	private int RequestIngredient(string[] Ingredients)
    	{
    		int choice = 1;
    		
    		do 
    		{
    			try 
    			{
    				Console.WriteLine("Do you want an ingredient or not");
    				for(int i = 0; i < 4; i++)
    					Console.WriteLine("{0} - {1}", i+1, Ingredients[i]);
    				Console.Write("Your Choice? ");
    				choice = int.Parse(Console.ReadLine());
    			}
    			catch(FormatException)
    			{
    				Console.WriteLine("You must enter a valid number and no other character!");
    			}
    
    			if( choice < 1 || choice > 4 )
    				Console.WriteLine("Invalid Choice - Try Again!");
    		} while( choice < 1 || choice > 4 );
    
    		return choice;
    	}
    
    	private int GetTheNumberOfScoops()
    	{
    		int number = 1;
    
    		do
    		{
    			try 
    			{
    				Console.Write("How many scoops(1, 2, or 3)? ");
    				number = int.Parse(Console.ReadLine());
    			}
    			catch(FormatException)
    			{
    		Console.WriteLine("You must enter a valid number and no other character!");
    			}
    
    			if( number < 1 || number > 3 )
    				Console.WriteLine("Invalid Choice - Try Again!");
    		} while( number < 1 || number > 3 );
    
    		return number;
    	}
    
    	public void ProcessAnOrder()
    	{
    		int dFlv   = 0,
    			dCont  = 0,
    			dIngrd = 0;
    		int Scoops = 0;
    		decimal PriceIngredient, PriceScoop, TotalPrice;
    
    		string[] Flavor = new string[6];		
    		string[] Container = new string[3];
    		string[] Ingredient = new string[4];
    
    		Container[0] = "Cone";
    		Container[1] = "Cup";
    		Container[2] = "Bowl";
    
    		PrepareFlavors(Flavor);
    		CreateIngredients(Ingredient);
    
    		dFlv   = RequestFlavor(Flavor);
    		dCont  = ChooseContainer(Container);
    		dIngrd = RequestIngredient(Ingredient);
    		Scoops = GetTheNumberOfScoops();
    
    		if( dIngrd == 2 || dIngrd == 3 || dIngrd == 4 )
    			PriceIngredient = 0.50M;
    		else
    			PriceIngredient = 0.00M;
    
    		if( Scoops == 1 )
    			PriceScoop = 0.65M;
    		else if( Scoops == 2 )
    			PriceScoop = 1.05M;
    		else
    			PriceScoop = 1.55M;
    
    		Console.WriteLine("Ice Cream Vendor Machine");
    
    		TotalPrice = BasePrice + PriceScoop + PriceIngredient;
    
    		DisplayReceipt(Flavor[dFlv-1], Container[dCont-1],
    			           Ingredient[dIngrd-1], Scoops, TotalPrice);
    	}
    
    	public void DisplayReceipt(string Flv, string Cont, string Ingrd,
    		int spoons, decimal TotalPrice)
    	{
    		Console.WriteLine("\nIce Cream Order");
    		Console.WriteLine("Flavor:      {0}", Flv);
    		Console.WriteLine("Container:   {0}", Cont);
    		Console.WriteLine("Ingredient:  {0}", Ingrd);
    		Console.WriteLine("Scoops:      {0}",   spoons);
    		Console.WriteLine("Total Price: {0:C}\n", TotalPrice);
    	}
    }
  2. Save, compile, and test the program. Then return to Notepad

Returning an Array From a Method

Like a normal variable, an array can be returned from a method. This means that the method would return a variable that carries various values. When declaring or defining the method, you must specify its data type. When the method ends, it would return an array represented by the name of its variable.

To declare a method that returns an array, on the left of the method's name, provide the type of value that the returned array  will be made of, followed by empty square brackets. Here is an example:

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            Double[] number = new Double[5];

            DisplayNumber(number);
        }

        static Double[] InitializeList()
        {
        }

        static void DisplayNumber(Double[] n)
        {
            for (int i = 0; i < 5; i++)
                Console.WriteLine("Number {0}: {1}", i, n[i]);
        }
    }
}

Remember that a method must always return an appropriate value depending on how it was declared. In this case, if it was specified as returning an array, then make sure it returns an array and not a regular variable. One way you can do this is to declare and possibly initialize a local array variable. After using the local array, you return only its name (without the square brackets). Here is an example:

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            Double[] number = new Double[5];

            DisplayNumber(number);
            Console.ReadLine();
        }

        static Double[] InitializeList()
        {
            Double[] nbr = new Double[5];

            nbr[0] = 12.44;
            nbr[1] = 525.38;
            nbr[2] = 6.28;
            nbr[3] = 2448.32;
            nbr[4] = 632.04;

            return nbr;
        }

        static void DisplayNumber(Double[] n)
        {
            for (int i = 0; i < 5; i++)
                Console.WriteLine("Number {0}: {1}", i, n[i]);
        }
    }
}

When a method returns an array, that method can be assigned to an array declared locally when you want to use it. Remember to initialize a variable with such a method only if the variable is an array. If you initialize an array variable with a method that doesn't return an array, you would receive an error.

Here is an example:

#region Using directives

using System;
using System.Collections.Generic;
using System.Text;

#endregion

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Double[] number = new Double[5];

            number = InitializeList();
            DisplayNumber(number);
            
            Console.ReadLine();
        }

        static Double[] InitializeList()
        {
            Double[] nbr = new Double[5];

            nbr[0] = 12.44;
            nbr[1] = 525.38;
            nbr[2] = 6.28;
            nbr[3] = 2448.32;
            nbr[4] = 632.04;

            return nbr;
        }

        static void DisplayNumber(Double[] n)
        {
            Console.WriteLine("List of Numbers");
            for (int i = 0; i < 5; i++)
                Console.WriteLine("Number {0}: {1}", i, n[i]);
        }
    }
}

Practical LearningPractical Learning: Returning an Array From a Method

  1. To apply an example of returning an array from a method, and to complete this exercise change the Order.cs file as follows:
     
    using System;
    
    class IceCream
    {
    	public const decimal BasePrice = 1.55M;
    	
    	int ChoiceFlavor;
    	int ChoiceContainer;
    	int ChoiceIngredient;
    	int Scoops;
    	decimal TotalPrice;
    
    	private string[] PrepareFlavors()
    	{
    		string[] Flavors = new string[10];
    
    		Flavors[0] = "Vanilla";
    		Flavors[1] = "Cream of Cocoa";
    		Flavors[2] = "Chocolate Chip";
    		Flavors[3] = "Organic Strawberry";
    		Flavors[4] = "Butter Pecan";
    		Flavors[5] = "Cherry Coke";
    		Flavors[6] = "Chocolate Brownies";
    		Flavors[7] = "Caramel Au Lait";
    		Flavors[8] = "Chunky Butter";
    		Flavors[9] = "Chocolate Cookie";
    
    		return Flavors;
    	}
    
    	private void CreateIngredients(ref string[] Ingredients)
    	{
    		Ingredients[0] = "No Ingredient";
    		Ingredients[1] = "Peanuts";
    		Ingredients[2] = "M & M";
    		Ingredients[3] = "Cookies";
    	}
    
    	private void ChooseContainer(ref string[] Containers)
    	{
    		Containers[0] = "Cone";
    		Containers[1] = "Cup";
    		Containers[2] = "Bowl";
    
    		do 
    		{
    			try 
    			{
    				Console.WriteLine("What type of container do you want?");
    				for(int i = 0; i < 3; i++)
    					Console.WriteLine("{0} - {1}", i+1, Containers[i]);
    				Console.Write("Your Choice? ");
    				ChoiceContainer = int.Parse(Console.ReadLine());
    			}
    			catch(FormatException)
    			{
    		Console.WriteLine("You must enter a valid number and no other character!");
    			}
    				
    			if( ChoiceContainer < 1 || ChoiceContainer > 3 )
    				Console.WriteLine("Invalid Choice - Try Again!");
    		} while( ChoiceContainer < 1 || ChoiceContainer > 3 );
    	}
    
    	private void RequestFlavor(ref string[] Flavors)
    	{
    		Flavors = PrepareFlavors();
    
    		do 
    		{
    			try 
    			{
    				Console.WriteLine("What type of flavor do you want?");
    				for(int i = 0; i < 10; i++)
    					Console.WriteLine("{0} - {1}", i+1, Flavors[i]);
    				Console.Write("Your Choice? " );
    				ChoiceFlavor = int.Parse(Console.ReadLine());
    			}
    			catch(FormatException)
    			{
    		Console.WriteLine("You must enter a valid number and no other character!");
    			}
    				
    			if( ChoiceFlavor < 1 || ChoiceFlavor > 10 )
    				Console.WriteLine("Invalid Choice - Try Again!\n");
    		} while( ChoiceFlavor < 1 || ChoiceFlavor > 10 );
    	}
    
    	private void ProcessIngredients(ref string[] Ingredients)
    	{
    		CreateIngredients(ref Ingredients);
    		
    		do 
    		{
    			try 
    			{
    				Console.WriteLine("Do you want an ingredient or not");
    				for(int i = 0; i < 4; i++)
    					Console.WriteLine("{0} - {1}", i+1, Ingredients[i]);
    				Console.Write("Your Choice? ");
    				ChoiceIngredient = int.Parse(Console.ReadLine());
    			}
    			catch(FormatException)
    			{
    		Console.WriteLine("You must enter a valid number and no other character!");
    			}
    
    			if( ChoiceIngredient < 1 || ChoiceIngredient > 4 )
    				Console.WriteLine("Invalid Choice - Try Again!");
    		} while( ChoiceIngredient < 1 || ChoiceIngredient > 4 );
    	}
    
    	private void GetTheNumberOfScoops()
    	{
    		do
    		{
    			try 
    			{
    				Console.Write("How many scoops(1, 2, or 3)? ");
    				Scoops = int.Parse(Console.ReadLine());
    			}
    			catch(FormatException)
    			{
    		Console.WriteLine("You must enter a valid number and no other character!");
    			}
    
    			if( Scoops < 1 || Scoops > 3 )
    				Console.WriteLine("Invalid Choice - Try Again!");
    		} while( Scoops < 1 || Scoops > 3 );
    	}
    
    	public void ProcessAnOrder()
    	{
    		decimal PriceIngredient, PriceScoop;
    
    		string[] Flavor = new string[10];	
    		string[] Container = new string[3];
    		string[] Ingredient = new string[4];
    
    		RequestFlavor(ref Flavor);
    		ChooseContainer(ref Container);
    		ProcessIngredients(ref Ingredient);
    		GetTheNumberOfScoops();
    
    		if( ChoiceIngredient == 2 || ChoiceIngredient == 3 || ChoiceIngredient == 4 )
    			PriceIngredient = 0.50M;
    		else
    			PriceIngredient = 0.00M;
    
    		if( Scoops == 1 )
    			PriceScoop = 0.65M;
    		else if( Scoops == 2 )
    			PriceScoop = 1.05M;
    		else
    			PriceScoop = 1.55M;
    
    		Console.WriteLine("Ice Cream Vendor Machine");
    
    		TotalPrice = BasePrice + PriceScoop + PriceIngredient;
    
    		DisplayReceipt(ref Flavor, ref Container, ref Ingredient);
    	}
    
    	public void DisplayReceipt(ref string[] Flv, ref string[] Cont, ref string[] Ingrd)
    	{
    		Console.WriteLine("\nIce Cream Order");
    		Console.WriteLine("Flavor:      {0}", Flv[ChoiceFlavor]);
    		Console.WriteLine("Container:   {0}", Cont[ChoiceContainer]);
    		Console.WriteLine("Ingredient:  {0}", Ingrd[ChoiceIngredient]);
    		Console.WriteLine("Scoops:      {0}",   Scoops);
    		Console.WriteLine("Total Price: {0:C}\n", TotalPrice);
    	}
    }
  2. Save, compile, and test the program. Then return to Notepad
 

Previous Copyright 2004-2005 FunctionX, Inc. Next