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:
else
must come immediately after the closing curly brace of an if statementelse
also has its own set of opening and closing curly braces to encapsulate lines of codeConsidering 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.
true
or false
.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.Found a bug in the documentation? Let us know at documentation@code.org