We can handle larger amounts of data by using arrays. They are just one way to handle text with C#, but they are common in many programming languages so you should know what they are and how to use them.
We'll also discuss loops and use them to cycle through the content stored in our arrays.
Arrays
If we wanted to create an application that printed out a grocery list, we could have a separate variable for each item. Our variable declarations might look like this:
using System; namespace GroceryList { class Program { static void Main() { string item1 = "banana"; string item2 = "orange"; string item3 = "avocado"; } } }
Because all of these variables are related, we can bundle them together as an array.
The separate variables from above written as an array could look like this:
using System; namespace GroceryList { class Program { static void Main() { string[] items = {"banana", "orange", "avocado" }; } } }
Array Declaration
Creating a string array is similar to creating a string variable. You declare the data type and an identifier.
Initializing and assigning values is different, however. Array values are enclosed within curly braces. Each value is separated by a comma.
For strings, each of the values must be enclosed in double quote marks.
string[] items = {"banana", "orange", "avocado" };
Values on Separate Lines
You can have all the elements on the same line, or each on a separate line. The next two code snippets produce the same result. You can declare an array either way.
string[] items = {"banana", "orange", "avocado" };
string[] items = { "banana", "orange", "avocado" };
If you have a lot of items or text, breaking up the space sometimes makes it easier to read and update. The compiler doesn't mind if you make your array more "human readable" by having values on different lines.
Alternative Array Declarations
There are two more ways can declare an array. If you aren't sure what the values will be that you are storing, you can declare an array with the identifier and size. You can also use a long form to create an array.
No Initial Values
In our previous example of an array, the grocery list, we initialized the values for the array. If we didn't know what values we wanted to store in the array, we could declare it like this instead:
string[] items = new string[3];
The 3 in the square brackets indicates the length of the array; that we'll be storing three values. An array's length is the total number of elements it can contain.
Long Form
You can also explicitly instantiate. Don't include the size of the array (that is determined by the number of values you are including inside the curly braces).
string[] items = new string[]{"banana", "orange", "avocado" };
Array Index Numbers
An array stores multiple elements in one entity. Each of the elements within the array has an index number. The value stored in each element can be accessed by the index number.
Arrays in C# are zero based. That means when we want to access the first element, we access element zero.
0 | 1 | 2 |
banana | orange | avocado |
This statement would print out the value stored at the index 0 (banana):
Console.WriteLine(items[0]);
If we wanted to write out the value of the second element (orange) to the console window, we could use this:
Console.WriteLine(items[1]);
More about Zero Based
Not all languages are zero based. In some the first element in an array (the array's "lower bound") is one by default.
In C# you can change the lower bound if you create an instance of the Array class using CreateInstance.
Assigning Array Values
To change an element's value, use the array's index number like this:
items[0] = "avocado";
Array Review and Summary
Review Array Structures
An array declaration starts with the data type.
string[] items = {"banana", "orange", "avocado" };
In this case we are going to hold strings. The square brackets indicate this is an array.
Next is an identifier - items. The identifier is a name you as a programmer decide; you can name your array what you think makes sense.
Then the assignment operator (the equal sign).
Inside the curly braces {} are the values. Each is a string and must be enclosed in quote marks. Commas separate each of the values. All of the elements within an array must be the same data type.
At the end of the statement is a semicolon.
Our string array starts at index 0. The value stored at 0 is "banana".
Because the array is zero based, and we have three elements, the index numbers are 0, 1, and 2.
(If you tried to access a value at index 3 you would see an error something like "An unhandled exception of type 'System.IndexOutOfRangeException' occurred ".)
- C# arrays are zero based. The index starts at 0. To access the first element, you would refer to it at index 0.
- If you create an array without providing any data, the array will be populated with default values for the type of data that you will be storing.
- Each array can only hold one type (i.e., you can't mix integers and strings in the same array).
- If you don't initialize the values, you need to specify the size of the array.
Arrays are a fixed size. In a few sections we'll look at an alternative to using arrays (Lists).
Quick Quiz
In the code below, what is the identifier?
string[] items = {"banana", "orange", "avocado" };
string[] items = {"banana", "orange", "avocado" };
If we wanted to get the value "orange" printed to the console window, which statement below would we use?
Loops
If you have statements that need to repeat, you will probably want to use a loop structure. Loops make it easier to cycle through an array - especially if it holds a lot of data.
for
A for loop will cycle through statements until a condition is met. The basic form is:
for (initializer; condition; iterator)
body
The initializer sets the initial value that will be incremented or decremented. It acts as a counter. It is common in loops to have the counter variable named i or j. To cycle through our array, we will set ours to start at 0 with: i=0;.
Next is a condition. This is what is being tested to see if the loop continues, or stops. We want our loop to stop after it cycles through all the elements in our array. In the case of our GroceryList, which had 3 elements, the condition could look like: i < 3;.
Finally there is an iterator. This is what increments or decrements the variable that is acting as a counter. We could write i = i+1, but there is a short form for adding +1 to a variable. To cycle through our array we will increment the counter using: i++.
Example
Make a new project in Visual Studio and add the following example code to it. The first for loop will increment the counter with the shortcut i++ (the same as i = i+1). The second for loop decrements the counter with i--.
using System; namespace Count { class Program { static void Main() { Console.Title = "Examples of for loops"; //increment Console.WriteLine("Count 0 to 9!"); for (int i = 0; i < 10; i++) { Console.WriteLine(i); } //decrement Console.WriteLine("Count down 9 to 0!"); for (int j = 9; j > -1; j--) { Console.WriteLine(j); } Console.ReadKey(); } } }
You should see something that looks like this:
In the first loop, i++ adds one to the counter (counting up). In the second example, j-- decrements the counter (counting down).
Array Length
Remember when we discussed the Length property of the String class? Instead of manually writing how many times the loop should run, we can say the equivalent of "run the following statements for each element in the array". We can find out how many elements are in the array by using the Length property:
lunch.Length
Try out this example in Visual Studio.
using System; namespace Lunch { class Program { static void Main() { string[] lunch = new string[3]; lunch[0] = "sandwich"; for (int i=0; i<lunch.Length; i++) { Console.WriteLine("The value at " + i + " is " + lunch[i]); } Console.WriteLine("The value of lunch.Length is: " + lunch.Length); Console.ReadKey(); } } }
The for loop will cycle through all the items in the array, writing the values to the console window.
The value written to the console window for lunch.Length is 3 because we declared the array would hold 3 elements. Even without values assigned, the elements are still there.
Null Values
Strings are a reference type. If we don't give them values, they are null. If you'd like to learn more about what that means, here are some helpful links:
Replace the above example with the one below and run it again.
using System; namespace Lunch { class Program { static void Main() { string[] lunch = new string[3]; lunch[0] = "sandwich"; lunch[1] = "drink"; lunch[2] = "apple"; for (int i=0; i<lunch.Length; i++) { Console.WriteLine("The value at " + i + " is " + lunch[i]); } Console.ReadKey(); } } }
Instead of just seeing sandwich, we now also see drink and apple.
The foreach Statement
There are other ways of accessing elements in an array. Using foreach we can also write out array values to the console window.
Create a new project in Visual Studio and test out the example code below. The foreach statement makes it easy to print all the elements with just a few lines of code.
using System; namespace GroceryList { class Program { static void Main() { Console.Title = "Write Each Element in Array"; string[] items = { "banana", "orange", "avocado", "pretzels", "lemon", "pecans" }; foreach (string element in items) { Console.WriteLine(element); } Console.ReadLine(); } } }
The foreach has a set of parentheses that hold:
- a declaration of the data type that will be used
- an identifier
- the keyword "in"
- the name of the array to be accessed - in this case, "items"
Quick Quiz
How many values will be stored in this array?
string[] books = new string[9];
The code below will cause an error. Do you know why?
string[] books = new string[9]; books[0] = 4133587;
How did you do? Was your answer similar to this?
The array is declared as holding string values. On the second line, a number (integer) was used instead of a string.
If the number was inside of quote marks, marked as a string instead of a number, then there wouldn't be an error. The value would be read as a string and not as an integer.
string[] books = new string[9]; books[0] = "4133587";
Code Progress
At this point your project should have the branching narrative framework in the Choice() function, and from the walk-throughs you should have added design elements (color and/or ASCII art).
Consider having a "title screen" that displays the title and asks the player to press enter to start the game. After enter is pressed, the console window is cleared.
Code Example
Below is an example of framework progress (but with your content of course).
To Do: Practice Arrays and Loops
Assignments
- Back up your project.
- Add another method to your project that will show the end of the story. We'll also use it later to summarize what the player accomplished. Name it something like EndGame(). Call the new method at the end of StartGame(). Write out an instruction to press enter or return to exit out of the game, too. Code example below.
- Create a small application that prints out words to a public domain poem or song. Use arrays. Example below.
Example StartGame() and EndGame() Methods
Try writing the code on your own before looking at the example.
Poem Example
An example poem that is a modified version of "One and One are Two" by Christina Georgina Rossetti.
- Can you programmatically add the numbers?
- Is it possible to only use one variable to write out all the numbers?
- How would you chart the flow of the program?
1 and 1 are 2
Treats for me and you.
2 and 2 are 4
At the candy store.
3 and 3 are 6
Let's get a big mix.
4 and 4 are 8
The candy is so great.
5 and 5 are 10
Order treats again.
6 and 6 are 12
Life-size candy elf.
7 and 7 are 14
Lick our fingers clean.
8 and 8 are 16
Feeling kinda green.
9 and 9 are 18
Tummy getting mean.
10 and 10 are 20
Ate way too many!
11 and 11 are 22
Vomit on my shoe.
12 and 12 are 24
Candy nevermore!
Related example: C# Loops: Ten Bears Song.
Code Files
If you have errors, or just want to check how your code compares in terms of progress, the code examples for this chapter are linked below.
- 9.1 For Loops
- 9.2 For Loops
- 9.3 For Loops
- 9.4 For Each
- 9.5 Framework Progress
- 9.6 Framework Progress
Next Step
In the next section we'll use arrays to manage our content and a switch statement to show content depending on which choice the player has made.