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
Learning: Introducing Arrays |
|
- Start Microsoft Visual C# and create a Console
Application named IceCream1
- To save the project, on the Standard toolbar, click the Save All button
- Change the Solution Name to VendingMachine1
- To create a new class, on the main menu, click Project -> Add
Class...
- Set the Name to IceCreamOrder and press Enter
- Change the file as follows:
using System;
using System.Collections.Generic;
using System.Text;
namespace IceCream1
{
public class IceCreamOrder
{
public const decimal BasePrice = 1.55M;
public void ProcessAnOrder()
{
int dFlv = 0,
dCont = 0,
dIngrd = 0;
int Scoops = 0;
decimal PriceIngredient = 0.00M, TotalPrice = 0.00M;
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);
}
}
}
|
- Save the file
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 control? 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 of name 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 such as C/C++ or
Pascal), an array is considered a reference type. Therefore, an array
requests its memory using the new operator.
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. 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
Learning: Creating an Array |
|
- To create arrays, change the IceCreamOrder.cs file as follows:
uusing System;
namespace IceCream1
{
class IceCreamOrder
{
public const decimal BasePrice = 1.55M;
public void ProcessAnOrder()
{
int dFlv = 0,
dCont = 0,
dIngrd = 0;
int Scoops = 0;
decimal PriceIngredient = 0.00M, TotalPrice = 0.00M;
string[] Flavor = new string[6];
string[] Container = new string[3];
string[] Ingredient = new string[4];
Console.WriteLine("Ice Cream Vendor Machine");
. . . No Change
}
}
}
|
- Save the file
|
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 or an
element 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 array 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. In this case, 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
Learning: Using the Members of an Array |
|
- To initialize arrays and use their members, change the IceCreamOrder.cs
file as
follows:
using System;
namespace IceCream1
{
class IceCreamOrder
{
public const decimal BasePrice = 1.55M;
public void ProcessAnOrder()
{
int dFlv = 0,
dCont = 0,
dIngrd = 0;
int Scoops = 0;
decimal PriceIngredient = 0.00M, TotalPrice = 0.00M;
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("\n==================================");
Console.WriteLine("Ice Cream Order");
Console.WriteLine("----------------------------------");
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}", TotalPrice);
Console.WriteLine("==================================\n");
}
}
}
|
- Access the Program.cs file
- To test the IceCreamOrder class, change the file as follows:
using System;
namespace IceCream1
{
class Program
{
static int Main()
{
IceCreamOrder IS = new IceCreamOrder();
IS.ProcessAnOrder();
return 0;
}
}
}
|
- Execute the application and test it.
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? 5
What type of container do you want?
1 - Cone
2 - Cup
3 - Bowl
Your Choice? 3
Do you want an ingredient or not
1 - No Ingredient
2 - Peanuts
3 - M & M
4 - Cookies
Your Choice? 4
How many scoops(1, 2, or 3)? 3
==================================
Ice Cream Order
----------------------------------
Flavor: Cherry Coke
Container: Bowl
Ingredient: Cookies
Scoops: 3
Total Price: $5.30
==================================
Press any key to continue . . .
|
|
- Close the DOS window
|
|