×

c# · level 1 · unit 6 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A loop visits every item in an array.

A foreach loop hands you each item in turn, from first to last. foreach (int price in prices) reads as: for each int called price in prices, run the block.

The loop box gets the next item on every turn. No counting, no index, and it can never fall off the end of the array.

To add things up, keep a . Make a box holding 0 before the loop, then add each item to it inside the block, like a till adding up your shopping.

using System;

int[] prices = { 3, 5, 2 };
int total = 0;
foreach (int price in prices)
{
    total = total + price;
}
Console.WriteLine($"Total: {total}");

Name the loop box after one item, like price for prices, so the code reads well.