c# · level 1 · unit 6 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Watch the total grow. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
int[] dailySteps = { 3000, 4000, 2000 };
int total = 0;
foreach (int steps in dailySteps)
{
total = total + steps;
Console.WriteLine(total);
}
your turn
Your turn. Add up a football season.
Type how many goals your team scored in each of three matches, as whole numbers. Then press run to see the season total.
output
press run to see what happens
fix it
The total should be 20, but it says 4. Fix it!
output
press run to see what happens
- 4 is the last score. What happens to the total on each turn of the loop?
- Line 7 overwrites the total with each score, so only the last one is left. It should add to the total.
- Change line 7 to
total = total + score;, then press run.
nailed it
you can add up a whole array. :D
foreachhands you each item in turn.- Start a running total at 0 before the loop.
- Add each item with
total = total + item;.
new words in your collection
- foreach
- running total
This lesson isn’t saved. A free account remembers every lesson you finish.