ms_learn_csharp/009_arrays_forearc/009_csharp.md

22 KiB
Raw Blame History

Store and iterate through sequences of data using Arrays and the foreach statement in C#

Work with sequences of related data in data structures known as arrays. Then, learn to iterate through each item in the sequence.

Learning objectives

In this module, you will:

  • Create and initialize a new array.
  • Set and get values in arrays.
  • Iterate through each element of an array using the foreach statement.

Prerequisites

  • Experience with declaring and initializing variables and basic data types like string.
  • Experience with printing to output using Console.WriteLine().
  • Experience with string interpolation to combine literal strings with variable data.
  • Experience researching how to use methods from the .NET Class Library.

Introduction

C# arrays allow you to store sequences of values in a single data structure. In other words, imagine a single variable that can hold many values. Once you have a single variable that stores all the values, you can sort the values, reverse the order of the values, loop through each value and inspect it individually, and so on.

Suppose you work in the security department of a company that matches online sellers with commission-based advertisers. You've been asked to write C# code that will iterate through the Order IDs of incoming orders. You need to inspect each Order ID to identify orders that may be fraudulent. You'll need to implement arrays to accomplish this programming task.

In this module, you'll create and initialize arrays. You'll set and retrieve values from elements in an array accessing each element using its index. You'll create looping logic that allows you to work with each element in an array.

By the end of this module, you'll have worked with your first structure to hold multiple data values. Later, in other modules, you'll learn how to sort, filter, query, aggregate, and perform other operations on your data.


Exercise

Get started with array basics

Arrays can be used to store multiple values of the same type in a single variable. The values stored in an array are generally related. For example, a list of student names could be stored in a string array named students.

Your work in the security department is focused on finding a pattern for fraudulent orders. You want your code to review past customer orders and identify markers associated with fraudulent orders. Your company hopes the markers can be used to identify potential fraudulent purchase orders in the future before they're processed. Since you don't always know in advance how many orders you need to review, you can't create individual variables to hold each Order ID. How can you create a data structure to hold multiple related values?

In this exercise, you use arrays to store and analyze a sequence of Order IDs.

What is an array?

An array is a sequence of individual data elements accessible through a single variable name. You use a zero-based numeric index to access each element of an array. As you can see, arrays allow you to collect together similar data that shares a common purpose or characteristics in a single data structure for easier processing.

Declaring arrays and accessing array elements

An array is a special type of variable that can hold multiple values of the same data type. The declaration syntax is slightly different because you have to specify both the data type and the size of the array.

Prepare your coding environment

This module includes activities that guide you through the process of building and running sample code. You're encouraged to complete these activities using Visual Studio Code as your development environment. Using Visual Studio Code for these activities helps you to become more comfortable writing and running code in a developer environment that's used by professionals worldwide.

At the Terminal command prompt, to create a new console application in a specified folder, type:

dotnet new console -o ./path_to/project

You can use this C# console project to create, build, and run code samples during this module.

Declare a new array

To declare a new array of strings that can hold three elements, enter the following code:

string[] fraudulentOrderIDs = new string[3];

Take a minute to examine your code.

The new operator creates a new instance of an array in the computer's memory that can hold three string values. For more information about the new keyword, see the module "Call methods from the .NET Class Library using C#".

Notice that the first set of square brackets [] merely tells the compiler that the variable named fraudulentOrderIDs is an array, but the second set of square brackets [3] indicates the number of elements that the array can hold.

Note
This example demonstrates how to declare an array of strings, however, you can create an array of every data type including primitives like int and bool as well as more complex data types like classes. This example uses the simplicity of strings to minimize the number of new ideas you need to grasp as you're getting started.

Assign values to elements of an array

At this point, you've declared an array of strings, but each element of the array is empty. To access an element of an array, you use a numeric zero-based index inside of square brackets. You can assign a value to an array element using the = as if it were a regular variable.

To assign Order ID values to your fraudulentOrderIDs array, update your code as follows:

string[] fraudulentOrderIDs = new string[3];

fraudulentOrderIDs[0] = "A123";
fraudulentOrderIDs[1] = "B456";
fraudulentOrderIDs[2] = "C789";

Take a minute to examine your code.

Notice that you're using the name of the array to access array elements. Each element is accessed individually by specifying zero-based index number inside the square brackets.

Since your array is declared as a string, the values that you assign must also be strings. In this scenario, you're assigning Order IDs to the elements of the array.

Attempt to use an index that is out of bounds of the array

It might not seem intuitive at first, but it's important to remember that you 're declaring the count of elements in the array. However, you access each element of the array starting with zero. So, to access the second item in the array, you use index 1.

It's common for beginners to forget that arrays are zero-based and attempt to access an element of the array that doesn't exist. If you make this mistake, a runtime exception occurs informing you that you attempted to access an element that is outside the boundary of the array.

To intentionally "break" your application, attempt to access a fourth element of your array using index value of 3.

At the bottom of your code file, enter the following code line:

fraudulentOrderIDs[3] = "D000";

Ensure that your code matches this example:

string[] fraudulentOrderIDs = new string[3];

fraudulentOrderIDs[0] = "A123";
fraudulentOrderIDs[1] = "B456";
fraudulentOrderIDs[2] = "C789";
fraudulentOrderIDs[3] = "D000";

At the Terminal command prompt, to compile your code, type dotnet build and then press Enter.

You should see the following message:

Build succeeded.        
    0 Warning(s)        
    0 Error(s)

At the Terminal command prompt, to run your code, type dotnet run and then press Enter.

When you run the app, you get the following runtime error message:

Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.     
   at Program.<Main>$(String[] args) in C:\Users\someuser\Desktop\CsharpProjects\TestProject\Program.cs:line 6

Notice the following parts of the error:

  • Error message: System.IndexOutOfRangeException: Index was outside the bounds of the array.
  • Error location: Program.cs:line 6

Comment out the line that generated the runtime error.

// fraudulentOrderIDs[3] = "D000";

You've seen how to assign a value to an array element. Now look at how to access a value that's being stored in an array element.

Retrieve values from elements of an array

Accessing the value of an array element works the same way as assigning a value to an array element. You just specify the index of the element whose value you want to retrieve.

To write the value of each fraudulent Order ID, update your code as follows:

string[] fraudulentOrderIDs = new string[3];

fraudulentOrderIDs[0] = "A123";
fraudulentOrderIDs[1] = "B456";
fraudulentOrderIDs[2] = "C789";
// fraudulentOrderIDs[3] = "D000";

Console.WriteLine($"First: {fraudulentOrderIDs[0]}");
Console.WriteLine($"Second: {fraudulentOrderIDs[1]}");
Console.WriteLine($"Third: {fraudulentOrderIDs[2]}");

At the Terminal command prompt, type dotnet run and then press Enter.

You should see the following message:

First: A123
Second: B456
Third: C789

Reassign the value of an array

The elements of an array are just like any other variable value. You can assign, retrieve, and reassign a value to each element of the array.

At the end of your code file, to reassign and then print the value of the first array element, enter the following code:

fraudulentOrderIDs[0] = "F000";

Console.WriteLine($"Reassign First: {fraudulentOrderIDs[0]}");

Ensure that your code matches the following example:

string[] fraudulentOrderIDs = new string[3];

fraudulentOrderIDs[0] = "A123";
fraudulentOrderIDs[1] = "B456";
fraudulentOrderIDs[2] = "C789";
// fraudulentOrderIDs[3] = "D000";

Console.WriteLine($"First: {fraudulentOrderIDs[0]}");
Console.WriteLine($"Second: {fraudulentOrderIDs[1]}");
Console.WriteLine($"Third: {fraudulentOrderIDs[2]}");

fraudulentOrderIDs[0] = "F000";

Console.WriteLine($"Reassign First: {fraudulentOrderIDs[0]}");

At the Terminal command prompt, type dotnet run and then press Enter.

You should see the following message:

First: A123
Second: B456
Third: C789
Reassign First: F000

Initialize an array

You can initialize an array during declaration just like you would a regular variable. However, to initialize the elements of the array, you use a special syntax featuring curly braces.

Comment out the lines where you declare the fraudulentOrderIDs variable.

You can use a multi-line comment (/* ... */) to comment out the declaration of fraudulentOrderIDs and the lines used to assign values to the array elements.

To declare the array initialize values in a single statement, enter the following code:

string[] fraudulentOrderIDs = { "A123", "B456", "C789" };

Ensure that your code matches the following example:

/*
string[] fraudulentOrderIDs = new string[3];

fraudulentOrderIDs[0] = "A123";
fraudulentOrderIDs[1] = "B456";
fraudulentOrderIDs[2] = "C789";
// fraudulentOrderIDs[3] = "D000";
*/

string[] fraudulentOrderIDs = { "A123", "B456", "C789" };

Console.WriteLine($"First: {fraudulentOrderIDs[0]}");
Console.WriteLine($"Second: {fraudulentOrderIDs[1]}");
Console.WriteLine($"Third: {fraudulentOrderIDs[2]}");

fraudulentOrderIDs[0] = "F000";

Console.WriteLine($"Reassign First: {fraudulentOrderIDs[0]}");

Take a minute to examine the declaration statement.

Notice that this syntax is both compact and easy to read. When you run the application, there should be no change to the output.

At the Terminal command prompt, type dotnet run and then press Enter.

You should see the same message as before:

First: A123
Second: B456
Third: C789
Reassign First: F000

Use the Length property of an array

Depending on how the array is created, you may not know in advance how many elements an array contains. To determine the size of an array, you can use the Length property.

Note
The Length property of an array is not zero-based.

At the end of your code file, to report the number of fraudulent orders, enter the following code:

Console.WriteLine($"There are {fraudulentOrderIDs.Length} fraudulent orders to process.");

This code uses the array's Length property, an integer, to return the number of elements in your fraudulentOrderIDs array.

Ensure that your code matches this example:

/*
string[] fraudulentOrderIDs = new string[3];

fraudulentOrderIDs[0] = "A123";
fraudulentOrderIDs[1] = "B456";
fraudulentOrderIDs[2] = "C789";
// fraudulentOrderIDs[3] = "D000";
*/

string[] fraudulentOrderIDs = { "A123", "B456", "C789" };

Console.WriteLine($"First: {fraudulentOrderIDs[0]}");
Console.WriteLine($"Second: {fraudulentOrderIDs[1]}");
Console.WriteLine($"Third: {fraudulentOrderIDs[2]}");

fraudulentOrderIDs[0] = "F000";

Console.WriteLine($"Reassign First: {fraudulentOrderIDs[0]}");

Console.WriteLine($"There are {fraudulentOrderIDs.Length} fraudulent orders to process.");

Save the changes to your Program.cs file, and then run the application.

You should see the following output:

First: A123
Second: B456
Third: C789
Reassign First: F000
There are 3 fraudulent orders to process.

Recap

Here's the most important things to remember when working with arrays:

  • An array is a special variable that holds a sequence of related data elements.
  • You should memorize the basic format of an array variable declaration.
  • Access each element of an array to set or get its values using a zero-based index inside of square brackets.
  • If you attempt to access an index outside of the boundary of the array, you get a run time exception.
  • The Length property gives you a programmatic way to determine the number of elements in an array.

Exercise

Implement the foreach statement

Suppose you work for a manufacturing company. The company needs you to complete an inventory of your warehouse to determine the number of products that are ready to ship. In addition to the total number of finished products, you need to report the number of finished products stored in each individual bin in your warehouse, along with a running total. This running total will be used to create an audit trail so you can double-check your work and identify "shrinkage".

Looping through an array using foreach

The foreach statement provides a simple, clean way to iterate through the elements of an array. The foreach statement processes array elements in increasing index order, starting with index 0 and ending with index Length -

  1. It uses a temporary variable to hold the value of the array element associated with the current iteration. Each iteration will run the code block that's located below the foreach declaration.

Here's a simple example:

string[] names = { "Rowena", "Robin", "Bao" };
foreach (string name in names){
    Console.WriteLine(name);
}

Below the foreach keyword, the code block that contains the Console.WriteLine(name); will execute once for each element of the names array. As the .NET runtime loops through each element of the array, the value stored in the current element of the names array is assigned to the temporary variable name for easy access inside of the code block.

If you ran the code, you would see the following result.

Rowena
Robin
Bao

Use the foreach statement to create a sum of all the items on hand in each bin of your warehouse.

Create and initialize an array of int

To create an array of type int that stores the number of finished products in each bin, enter the following code:

int[] inventory = { 200, 450, 700, 175, 250 };

Add a foreach statement to iterate through the array

To create a foreach statement that iterates through each element of the inventory array, enter the following code:

foreach (int items in inventory){

}

Notice that the foreach statement temporarily assigns the value of the current array element to an int variable named items.

Ensure that your code matches the following:

int[] inventory = { 200, 450, 700, 175, 250 };

foreach (int items in inventory){

}

Add a variable to sum the value of each element in the array

Position the cursor on the blank code line above the foreach statement.

To declare a new variable that represents the sum of all finished products in your warehouse, enter the following code:

int sum = 0;

Ensure that you declare the variable outside of the foreach statement.

Position the cursor inside the code block of the foreach statement.

To add the current value stored in items to the sum variable, enter the following code:

sum += items;

Ensure your code matches the following:

int[] inventory = { 200, 450, 700, 175, 250 };
int sum = 0;
foreach (int items in inventory){
    sum += items;
}

Display the final value of sum

Create a blank code line below the code block of the foreach statement.

To report the final sum of items in your inventory, enter the following code:

Console.WriteLine($"We have {sum} items in inventory.");

Ensure that your code matches the following:

int[] inventory = { 200, 450, 700, 175, 250 };
int sum = 0;
foreach (int items in inventory){
    sum += items;
}

Console.WriteLine($"We have {sum} items in inventory.");

At the Terminal command prompt, type dotnet run and then press Enter.

We have 1775 items in inventory.

Create a variable to hold the current bin number and display the running total

To fulfill the final requirement of your inventory reporting project, you'll need to create a variable that will hold the current iteration of the foreach statement so you can display the bin and the count of finished items in that bin, along with the running total of all items of bins accounted for so far.

Create a blank code line above the foreach statement.

To declare int variable named bin that's initialized to 0, enter the following code:

int bin = 0;

You will use bin to store the number of the bin whose inventory is currently being processed.

Inside the foreach code block, to increment bin each time the code block is executed, enter the following code:

bin++;

Notice that you use the ++ operator to increment the value of the variable by 1. This is a shortcut for bin = bin + 1.

To report the bin number, the number of finished products in the bin, and the running total of finished products, enter the following code inside the foreach code block, after bin++;:

Console.WriteLine($"Bin {bin} = {items} items (Running total: {sum})");

This code will use your counter variable bin, the temporary foreach variable items, and your sum variable to report the current state of your inventory in a nicely formatted message.

Ensure that your code matches the following:

int[] inventory = { 200, 450, 700, 175, 250 };
int sum = 0;
int bin = 0;
foreach (int items in inventory){
    sum += items;
    bin++;
    Console.WriteLine($"Bin {bin} = {items} items (Running total: {sum})");
}
Console.WriteLine($"We have {sum} items in inventory.");

Save the changes to your Program.cs file, and then run the application.

You should see the following output:

Bin 1 = 200 items (Running total: 200)
Bin 2 = 450 items (Running total: 650)
Bin 3 = 700 items (Running total: 1350)
Bin 4 = 175 items (Running total: 1525)
Bin 5 = 250 items (Running total: 1775)
We have 1775 items in inventory.

Recap

Here's a few things to remember about foreach statements and incrementing values that you learned in this unit:

  • Use the foreach statement to iterate through each element in an array, executing the associated code block once for each element in the array.
  • The foreach statement sets the value of the current element in the array to a temporary variable, which you can use in the body of the code block.
  • Use the ++ increment operator to add 1 to the current value of a variable.

Exercise

Complete a challenge activity for nested iteration and selection statements

Code challenges reinforce what you've learned and help you gain some confidence before continuing on.

Fraudulent order challenge

Earlier in this module, you set out to write code that would store Order IDs belonging to potentially fraudulent orders. Your goal is to find fraudulent orders as early as possible and flag them for deeper analysis.

Code challenge

Report the Order IDs that need further investigation

Your team has found a pattern. Orders that start with the letter "B" encounter fraud at a rate 25 times greater than the normal rate. You write new code that outputs the Order ID of new orders where the Order ID starts with the letter "B". This will be used by the fraud team to investigate further.

Use the following steps to complete this challenge.

Declare an array and initialize it to contain the following elements:

B123
C234
A345
C15
B177
G3003
C235
B179

These values represent the fraudulent Order ID data that your application use.

Create a foreach statement to iterate through each element of your array.

Report the Order IDs that start with the letter "B".

You need to evaluate each element of the array. Report the potentially fraudulent Order IDs by detecting the orders that start with the letter "B". To determine whether or not an element starts with the letter "B", use the String.StartsWith() method. Here's a simple example of how to use the String.StartsWith() method that you can adapt for your code:

string name = "Bob";
if (name.StartsWith("B")){
    Console.WriteLine("The name starts with 'B'!");
}

Your output should match the following:

B123
B177
B179

Tip
Here's a hint: As you loop through each element in your array, you'll need an if statement. The if statement will need to use a method on the string class to determine if a string starts with a specific letter. If you're not sure how to use an if statement, please see the module "Add decision logic to your code using the if-elseif-else statement in C#".