If-Else Statements

How If-Else Statements work

With an if-else statement you are giving an either-or command:

either the lines of code inside the if will execute or the lines inside the else will execute. Those are the options.

You saw in the video how to add an else clause to an if-statement -- hit the little + symbol on the tail of the if statement.

Inside the curly braces for the else clause you put lines of code that you want to run if the Boolean condition from the if statement is false.

Some important notes about the else clause:

  • The else must come immediately after the closing curly brace of an if statement
  • The else also has its own set of opening and closing curly braces to encapsulate lines of code



Considering our flow chart from before, until now we haven't had a way to make the program do something different if the condition was false. With an if-else statement we do.

We can now write a program that "branches" at a particular point, running one of two possible sections of code.

 

A Worked Example

 

  1. Lines of code execute sequentially as usual. Prompt the user to enter their age.
  2. The if statement and Boolean expression are also the same as before. The expression evaluates to either true or false.
  3. With an if-else statement you are guaranteeing that exactly one of these two sections of code will execute. If the condition is true (age is 18 or greater) then the lines of code inside the if-statement's curly braces are executed. If the condition is false it jumps to the else clause and executes any lines of code it finds between the else clause's curly braces.
  4. Finally the program picks up normal execution directly after the if-else block. At this point in the program, we know that either the code in the if-block or the else block has executed.

Found a bug in the documentation? Let us know at documentation@code.org