So far, we’ve talked about if() statements and if/else statements to handle the flow of code execution in our programs. These tools are handy, but they’re not enough to handle the sorts of sophisticated logic that most programs require.
Consider the following situations:
What do all of these situations have in common? They will all require code that is run repeatedly many times.
This is where loops come in. In C#, they come in two basic forms: while loops, and for loops:
Let’s jump right in with a simple example of a ‘while’ loop.
This loop will print numbers to the console from 1 to 100:
This is called a “while” loop, and if you think its structure is similar to an if() statement, you’re right! A while loop consist of:
In this example, the number gets incremented by one each loop = so once it reaches 101, then the loop condition is no longer true.
Crucially - there needs to be code inside the function that will allow the loop to eventually exit - otherwise you’ll be stuck in an infinite loop!
Here’s another example of a while loop to handle a simple password entry:
There are a couple things to notice here:
First - we are using the “!” symbol in our while() loop, which means “NOT”. In other words, the expression:
!enteredCorrectPassword
is true, if enteredCorrectPassword is false, and false if the variable is true.
Second - We have an if() statement inside our while() loop. You can ‘nest’ if statements inside loops, loops inside if() statements, and even put multiple “nested” if statements inside each other!