Arrays and foreach statements. Introduction to Programming. C# — Lesson Seven(7)
Ferdinand Charles
Full Stack Software Engineer | AI/ML Engineer | Prompt Engineering Specialist| Large Language Model Whisperer | Digital Transformation Consultant | Cloud Solutions Architect | DevOps Practitioner | TensorFlow | AWS
UNIT 1
Store and iterate through sequences of data using Arrays and the foreach statement in C#
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 we work in the anti-fraud department of a company that matches online sellers with commission-based advertisers. We’ve been asked to write C# code that will iterate through the Order IDs of incoming orders. We need to inspect each Order ID to identify orders that may be fraudulent. How can we programmatically collect a sequence of OrderIDs, then iterate through and process each Order ID?
In this lesson, 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 lesson, you’ll have worked with your first structure to hold multiple data values. Later, in other lesson, you’ll learn how to sort, filter, query, aggregate, and perform other operations on your data.
Learning objectives
In this lesson 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 on docs.microsoft.com
UNIT 2
Exercise — Array Basics
Suppose we work in the anti-fraud department of a company that matches online sellers with commission-based advertisers. Our advertisers have notified us of a rash of recent credit card chargebacks. These chargebacks occur a few months after commissions were paid out, long after the thieves have vanished. We’ve been asked to review several orders in hopes of identifying markers of fraud. Maybe our company can use those markers in the future to identify potential fraudulent purchases.
We need to work with a sequence of Order IDs. These orders are related in as much as we want to identify and analyze them looking for common characteristics. Because we don’t always know in advance how many orders we’ll need to review, we can’t create individual variables to hold each Order ID. How can we create a data structure to hold multiple related values?
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’ll see, arrays allow us to collect together similar data that shares a common purpose or characteristics in a single data structure for easier processing.
Declaring arrays
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.
Step 1 — Declare a new array
To declare a new array of strings that will hold three elements, type the following C# statement into your editor.
string[] fraudulentOrderIDs = new string[3];
The new operator creates a new instance of an array in the computer’s memory that can hold three string values.
Notice that the first set of square brackets [] merely tells the compiler that the variable named fraudulentOrderIDs will be an array, but the second set of square brackets [3] contains the number of elements that the array will hold.
Note: — While this example only declares an array of strings, 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.
Assigning Values to Elements of an Array
At this point, we’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 assign a value using the = assignment value as if it were a regular variable.
Step 2 — Assign values to elements on an array
Modify the code from Step 1 to match the following code snippet. The following code will assign Order IDs to each element of the array.
string[] fraudulentOrderIDs = new string[3];
fraudulentOrderIDs[0] = "A123";
fraudulentOrderIDs[1] = "B456";
fraudulentOrderIDs[2] = "C789";
Step 3 — 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 we’re declaring the count of elements in the array. However, we access each element of the array starting with zero. So, to access the second item in the array, we 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. When this happens, you’ll experience a runtime exception that you attempted to access an element that is outside the boundary of the array.
Let’s intentionally break our application by attempting to access a fourth element of our array using the index 3. Modify the code from Step 2 by adding the following line of code.
fraudulentOrderIDs[3] = "D000";
The entire code example should now match what you see that follows.
string[] fraudulentOrderIDs = new string[3];
fraudulentOrderIDs[0] = "A123";
fraudulentOrderIDs[1] = "B456";
fraudulentOrderIDs[2] = "C789";
fraudulentOrderIDs[3] = "D000";
When you run the app, you’ll get a long error message. Focus on the first two lines. You’ll see the following error message. Pay particular attention to the sentence that includes the word array.
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. — -> System.IndexOutOfRangeException: Index was outside the bounds of the array.
Now, comment out the line of code you just added in this step.
// fraudulentOrderIDs[3] = "D000";
Getting Values of Elements in an Array
You get a value from an element of an array in the same manner. Use the index of the element to retrieve its value.
Step 4 — Retrieve values of an array
Modify the code from Step 3 to write out the value of each fraudulent Order ID using string interpolation. Your code should match the following passage of code.
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]}");
Run the code. You should see the following output.
First: A123 Second: B456 Third: C789
Step 5 — Reassign the value of an array
The elements of an array are just like any other variable value in as much as you can assign, retrieve, and reassign a value to each element of the array.
Add the following lines of code inside to bottom of your editor. Here, you’ll reassign the value of the first element in the array, then print it out.
fraudulentOrderIDs[0] = "F000";
Console.WriteLine($"Reassign First: {fraudulentOrderIDs[0]}");
Your editor should match the following passage of code.
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]}");
When you run the code, you should see the following output.
First: A123 Second: B456 Third: C789 Reassign First: F000
Initializing an Array
Just like you can initialize a variable at the time you declare it, you can initialize a new array at the time you declare it using a special syntax featuring curly braces.
Step 6 — Initialize an array
Use a multi-line comment (/*?… */) to comment out the lines where you declare the fraudulentOrderIDs variable and assign each of its elements a value. Then, add the following line that declares and initializes the array with the same values all in a single line of code.
string[] fraudulentOrderIDs = { "A123", "B456", "C789" };
So, your code should now match what you see in the following passage.
/* 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]}");
When you run the application, there will be no change to the output.
First: A123 Second: B456 Third: C789 Reassign First: F000
Getting the Size 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.
Step 7 — Print the number of fraudulent orders using the array’s Length property
Modify the code from Step 6 adding the following line of code to the bottom of your editor.
Console.WriteLine($"There are {fraudulentOrderIDs.Length} fraudulent orders to process.");
Your code should now match the following code passage.
/* 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.");
When you run the code, 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.
1. An array is a special variable that holds a sequence of related data elements.
2. You should memorize the basic format of an array variable declaration.
3. Access each element of an array to set or get its values using a zero-based index inside of square brackets.
4. If you attempt to access an index outside of the boundary of the array, you’ll get a run time exception.
领英推荐
5. The Length property gives you a programmatic way to determine the number of elements in an array.
UNIT 3
Exercise — foreach Statement
Suppose we work for a manufacturer and need to take an inventory of our warehouse to determine the current number of finished products we have that are ready to ship. In addition to the total number of finished products, we may also want to print out a count and running total of each individual bin in our warehouse where our finished products are stored. This running total printout would create an audit trail so we can double-check our work and identify shrinkage.
Looping through an array using foreach
The foreach statement loops through each element in an array, running the code block below its declaration, substituting the value in a temporary variable for the value of the array that the current loop represents.
Here’s a simple example:
string[] names = { "Bob", "Conrad", "Grant" };
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 run the code, you would see the following result.
Bob Conrad Grant
Let’s use the foreach statement to create a sum of all the items on hand in each bin of our warehouse.
Step 1 — Create and initialize an array of int
Delete or comment out any code from previous exercises and add the following code to create an array of int that will store the number of finished products in each bin.
int[] inventory = { 200, 450, 700, 175, 250 };
Step 2 — Add a foreach statement to iterate through the array
Next, add a foreach statement that iterates through each element of the inventory array, temporarily assigning the value of the current element to the variable items. Your code should match the following listing.
int[] inventory = { 200, 450, 700, 175, 250 };
foreach (int items in inventory) { }
Step 3 — Add a variable to sum the value of each element in the array
Define a new variable that represents the sum of all finished products in our warehouse. Make sure to add it outside of the foreach statement.
int sum = 0;
Inside of the foreach statement, add the following line of code that adds the current value stored in items to the sum variable.
sum += items;
Make sure your code matches the following passage of code.
int[] inventory = { 200, 450, 700, 175, 250 };
int sum = 0;
foreach (int items in inventory)
{
sum += items;
}
Step 4 — Below the foreach statement’s code block, add the following statement that prints the final sum of items in inventory.
Console.WriteLine($"We have {sum} items in inventory.");
Make sure your code matches the following passage of code.
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.");
When you run the code, you should see the following output.
We have 1775 items in inventory.
Step 5 — Create a variable to hold the current bin number and display the running total iteration of the foreach statement so we 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.
Above the foreach statement, declare and initialize a new variable of type int to store the current number of the bin whose inventory is being processed.
int bin = 0;
Inside of the foreach code block, increment the bin each time the code block is executed.
bin++;
The ++ operator increments the value of the variable by 1. Its shortcut to writing bin = bin + 1.
Finally, inside of the foreach, display the bin, its count of finished products, and the running total of finished products in a nicely formatted message.
Console.WriteLine($"Bin {bin} = {items} items (Running total: {sum})");
Make sure your code matches the following passage of code.
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.");
When you run the code, you should see the following output.
OutputCopy 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 the foreach statement and other things we learned about in this unit.
1. Use the foreach statement to iterate through each element in an array, executing the associated code block once for each element in the array.
2. 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.
3. Use the ++ increment operator to add 1 to the current value of a variable.
UNIT 4
Challenge
Previously, we set out to write code that would store Order IDs belonging to potentially fraudulent orders. Our hope is to find fraudulent orders as early as possible and flag them for deeper analysis.
Our team found a pattern. Orders that start with the letter “B” encounter fraud 25 times the normal rate. We will write new code that will output the Order ID of new orders where the Order ID starts with the letter “B”. This will be used by our fraud team to investigate further.
Step 1 — Delete the code from the previous exercises. Select all of the code, then select the backspace or del key on your keyboard.
Step 2 — Declare and initialize a new array to hold fake Order IDs. Here’s the fake Order ID data that you should use to initialize your array.
B123 C234 A345 C15 B177 G3003 C235 B179
Step 3 — Iterate through each element of the array.
Use a foreach statement to iterate through each element of the array you just declared and initialized.
Step 4 — If the fake Order ID starts with “B”, then print the Order ID to the output.
Evaluate each element of the array. Identify and print to output the potentially fraudulent Order IDs looking for those orders that start with the letter “B”. The output should match the following output:
B123 B177 B179
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 so you can use it in your code:
string name = "Bob";
if (name.StartsWith("B"))
{
Console.WriteLine("The name starts with 'B'!");
}
Important
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 click here.
UNIT 5
Solution
The following code is one possible solution for the challenge from the previous unit.
string[] orderIDs = { "B123", "C234", "A345", "C15", "B177", "G3003", "C235", "B179" };
foreach (string orderID in orderIDs)
{
if (orderID.StartsWith("B"))
{
Console.WriteLine(orderID);
}
}
This code is merely “one possible solution” because a lot depends on how you decided to implement the logic. As long as you got the right results per the rules in the challenge, and you used an array and a foreach statement, then you did great!
If you succeeded, congratulations! Proceed to next lesson
Important
If you had trouble completing this challenge, maybe you should review the previous units before you continue on. All new ideas we discuss in other lessons will depend on your understanding of the ideas that were presented in this lesson.
UNIT 6
Summary
In our scenario, we needed to work with a sequence of Order IDs programmatically to identify potentially fraudulent orders. We created an array of Order IDs, then iterated through each element of the sequence looking for a common fraud trait.
C# Arrays allowed us to store each Order ID as an element of an array. We addressed a specific element of the array using an index — a zero-based numeric value. We could retrieve and set the value in each element. We iterated through the elements of the array to inspect or output each element’s value.
Imagine how difficult it would be to handle related data in our code if we didn’t have a structure like an array? We would need to know ahead of time just how many data elements we expected to work with and define a separate variable for each value. That would create a brittle solution.
Arrays can be sized when created according to the amount of data we need to work with. In other lessons, you’ll learn how to add or remove the number of elements from arrays at run time. You’ll learn how to sort, filter, query, and aggregate values in arrays. You’ll learn how to split a string into an array based on some delimiter. As you get even more familiar with arrays (and similar data structures), you’ll use them frequently when you need to flexibly work with data in your applications.
Thank for your time and thank you for reading. see you in the next article.