c# · level 1 · unit 5 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A loop keeps going while something is true.
A while loop is like an if that keeps coming back. It checks its condition, runs its block, then checks again. It stops the first time the condition is false.
Often a keeps track: a number box that changes each turn, like cookies = cookies - 1;. When it runs out, the condition turns false and the loop ends.
Forget to change the counter and the condition stays true forever. That is an : the program never finishes. Make sure something in the block moves it towards the end.
using System;
int cookies = 3;
while (cookies > 0)
{
cookies = cookies - 1;
Console.WriteLine($"Nom! Cookies left: {cookies}");
}
Console.WriteLine("All gone!"); A run that never ends is stopped after 10 seconds, so always check your counter.
guess first
Countdown time. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
int count = 3;
while (count > 0)
{
Console.WriteLine(count);
count = count - 1;
}
Console.WriteLine("Blast off!");
your turn
Your turn. Bottles on the wall.
Choose how many bottles start on the wall, and how many fall each time. Make that second number at least 1, or the song never ends!
output
press run to see what happens
fix it
The race never starts. Can you fix it?
output
press run to see what happens
- Only Race over! appears, so the block never runs, not even once. Check the condition on line 4.
lapstarts at 1. Is 1 more than 3? The condition isfalsestraight away.- Change
lap > 3tolap <= 3on line 4, then press run.
nailed it
your loops know when to stop. :D
whilerepeats its block while the condition istrue.- A counter moves the loop towards its end.
- If the condition never turns
false, the loop never ends.
new words in your collection
- while
- counter
- infinite loop
This lesson isn’t saved. A free account remembers every lesson you finish.