Sometimes, you only want parts of your code to run if a certain condition is met. For instance - if you sign into an app but supply the wrong password, you’re taken to a different screen than if you had provided the right one.
This area of programming is called Control Flow.
The most common form of control flow you’ll see in code is called an “if statement”. Let’s jump right in with an example to demonstrate how it works.
Imagine you’re writing a game, and you’ve ‘re handling the logic for whether the player won the game or lost.
that if statement is an example of control flow. If the value between the parenthesis (in this case, the ‘wonGame’ bool variable) is true, then the code between the curly braces will execute.
Otherwise, excecution will pass right over that whole section.
We can expand on this concept, by adding an else statement. If the condition for the if statement evaluates to false, thent the code in the else block will run instead.
when using if() statements, you can put anything in between the parenthesis, as long as it evaluates to a true/false value.
Now that we’re working with control flow, ‘bool’ values (true/false values) are going to become more important. But what if we need to handle more sophisticated decisions about control flow?
As an example: Let’s say you are writing code to let the user set a password for an account in an app.
You might need to check the following to decide if the password is valid:
The password is at least 10 characters long.
AND
The password contains at least one letter.
AND
The password contains at least one number.
if all three of these conditions are ‘true’, then the password is correct.
This is where boolean operators come in.
The three most common boolean operators are:
AND (&&)
OR (||)
NOT (!)
It can be a little confusing to explain these, so here are some examples of these operators in action:
Write if or if/else statements to handle the following: