Lesson Weekend

In Intro, we typically used two types of JavaScript loops: for and forEach(). forEach() loops iterate through each item in an array whereas for loops are more manual: we had to define how and when the loop starts and stops.

C# also features both for and for each loops, although the syntax does differ. This lesson will walk through for each loops. The next lesson will address for loops. Pay careful attention to the new, C#-specific syntax.

For Each Loops


For each loops cycle through an array and pinpoint each item. In JavaScript, we used for each loops like this:

var theEntireArray = ["zero index", "first index", "second index"];

theEntireArray.forEach(function(individualEntry){
  console.log(individualEntry);
});

However, doing the same thing in C# looks markedly different. First, defining a similar array in the REPL looks like this:

> string[] theEntireArray = {"zero index", "first index", "second index"};

To loop through this array and print each entry to the console, we'd use the following code:

foreach (string individualEntry in theEntireArray)
{
  Console.WriteLine(individualEntry);
}

When we run this loop in the REPL, it prints each individual string entry in the array:

zero index
first index
second index

Grocery Store Application

Let's practice C# for each loops more before moving on. We'll craft an application to manage a grocery list.

Create a new GroceryList.cs file with a GroceryList class name, a Main() method, and an array of grocery list items:

GroceryList.cs
using System;

class GroceryList
{
  static void Main()
  {
    string[] myGroceryList = {"eggs", "milk", "bread", "bananas", "cereal", "rice", "yogurt"};

  }
}

We can loop through each item in the myGroceryList array like this:

GroceryList.cs
using System;

class GroceryList
{
  static void Main()
  {
    string[] myGroceryList = {"eggs", "milk", "bread", "bananas", "cereal", "rice", "yogurt"};

    Console.WriteLine("My grocery list:");

    foreach (string groceryItem in myGroceryList)
    {
      Console.WriteLine(groceryItem);
    }

  }
}

The line foreach (string groceryItem in myGroceryList) can be read as "for each item in myGroceryList, name it groceryItem, then run the line of code between the curly braces." In this case, we're printing each item in myGroceryList to the console.

Looping Through ints

We can loop through any type of an array. Let's add functionality to keep track of our grocery trip's cost:

GroceryList.cs
using System;

class GroceryList
{
  static void Main()
  {
    string[] myGroceryList = {"eggs", "milk", "bread", "bananas", "cereal", "rice", "yogurt"};
    int[] groceryListPrices = { 3, 6, 4, 2, 4, 4};

    Console.WriteLine("My grocery list:");
    foreach (string groceryItem in myGroceryList)
    {
      Console.WriteLine(groceryItem);
    }

    int total = 0;
    foreach (int price in groceryListPrices)
    {
      total = total + price;
    }

    Console.WriteLine("Your total for this shopping trip will be $" + total);
  }
}
  • We create a second array int[] groceryListPrices to store the prices of myGroceryList items.

  • We create a new int variable named total and set it to 0. It's important we do this outside the loop, otherwise it will reset to 0 at the beginning of each loop iteration.

  • Inside the loop, we update total to equal total + price. price represents one item in groceryListPrices as the for each loop goes through each item in the array.

This pattern where we add to a variable and re-save the new value to that variable is so common there's an operator just for that: +=. total = total + price; is the same as total += price, just like in JavaScript.

Example For Each Loop:


> string[] theEntireArray = {"zero index", "first index", "second index"};

foreach (string individualEntry in theEntireArray)
{
  Console.WriteLine(individualEntry);
}

Lesson 8 of 9
Last updated more than 3 months ago.