c# · level 1 · unit 5 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Put an if inside a loop to check every number.
A loop's block can hold any code, an if. We say the if is inside the loop. The loop visits each number, and the if decides what to do with it.
Remember %, the remainder? A number is even when it splits into twos with nothing left over. So house % 2 == 0 is true for even numbers and false for odd ones.
To count matches, make a counter holding 0 before the loop. A box made inside a block only lives there, so it would vanish after every turn. That is its .
using System;
int leaflets = 0;
for (int house = 1; house <= 6; house++)
{
if (house % 2 == 0)
{
Console.WriteLine($"Leaflet for house {house}");
leaflets++;
}
}
Console.WriteLine($"Leaflets posted: {leaflets}"); Each extra block is indented four more spaces, so you can see what sits inside what.
guess first
Clap along. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
for (int beat = 1; beat <= 6; beat++)
{
if (beat % 3 == 0)
{
Console.WriteLine($"Clap on beat {beat}");
}
}
your turn
Your turn. Count the perfect groups.
Pick a group size from 2 to 10 and type it in the blank. The program counts how many numbers from 1 to 20 split into groups that size exactly.
output
press run to see what happens
fix it
The leaflet count has vanished. Can you fix it?
output
press run to see what happens
- C# says
leafletsdoes not exist on line 11. Where was that box made? - The box is made inside the loop's block, so its scope ends at that block's closing bracket.
- Move
int leaflets = 0;up above theforline, then press run.
nailed it
your loops can make decisions now. :D
- An
ifnested in a loop checks every turn. number % 2 == 0istruefor even numbers.- Make a counter before the loop, so it outlives the block.
new words in your collection
- nested
- even
- scope
This lesson isn’t saved. A free account remembers every lesson you finish.