1. While loops
We've seen how `for` and `foreach` loops help us repeat code a set number of times, usually when we know how many items we're working with. But sometimes, we don't know in advance how many times a loop needs to run. In those cases, we can use a `while` loop.
2. How while loop works
A while loop starts by checking the condition. If true, the code block runs and the condition is then checked again. This repeats until the condition becomes false, at which point the loop won't start again. It's useful when we want to keep looping until something happens, but we're not sure exactly when that will be.
3. while loop syntax
The syntax is simple. We start with the keyword while, followed by a condition in parentheses, and then a block of code in curly brackets -
just like an if statement.
But unlike if, which runs once, a while loop will run and check the condition again and again after each pass.
4. while loop example
Let's say we have a counter that starts at zero. We can write `while (counter < 5)`.
Inside the loop, we do something, like print the counter's value and then increase it by one.
5. Infinite while loop
If we forget to update the variable, or if the condition is always true, the loop will never end. That’s called an infinite loop, and it can cause our program to hang. So it’s important to make sure something inside the loop changes the condition over time.
6. Updating operators
To do that, we can use the `+=` operator to increment a variable. So we might write `counter += 3`. That's the same as saying `counter = counter + 3`.
There is also `-=`, `*=` or `/=` that work the same way.
7. Break
Just like with for loops, we can use the `break` keyword to exit a while loop early, even if the condition is still true. This gives us an extra level of control when we need it, although we usually can do without it.
8. Recap
In short, while loops are great when we don't know exactly how long something will take, but we know the condition we're waiting for.
9. Let's practice!
Now, you'll write a simple while loop and practice ending it using both a condition and the break keyword. Let's get started!