Conditional Statements

How Does Code Make Decisions?

We don’t always want to execute every line of code in our programs. We want our code to be able to make decisions.

For example, we may want to execute code if some condition is true (or false) or select an action based from a set of choices. For this, we use if and else statements.

if/else Statements

The foundation of conditional statements is the if and accompanying else statement. if allows us to selectively execute code if some condition is true. They consist of three parts:

  1. The keyword if

  2. A condition to check (inside ())

  3. A series of statements to execute if the condition is true (wrapped in {})

For example, we can test if the sum of two number is less that 10, and print out the result only if that is true:

The partner for the if statement is else. else allows us to specify actions to perform if the condition we checked with if was false. For example, we can add an else side to our code to print out “Number >= 10\n” if the if condition fails:

We can also chain multiple if and else statements together if we want to check multiple conditions:

If the first if condition is false, we move to the second (and so on and so forth).

It’s important to note that we only ever execute at most 1 block of code in an if/else chain. The block executed will be the first condition that resolves as true (or the else block if present and no condition resolves to true).

Relevant Links

Previous
Previous

Printing with the Standard Library