If/Else Statements

When you're writing a program, you often want what happens to depend on a set of rules that you establish. If this is true, do this thing. If it isn't, do this other thing. These are called conditional or if/else statements.

Every if/else statement begins with a test that returns (results in) either TRUE or FALSE. When the answer is TRUE, the code inside the { } runs. It's as simple as that.

One more thing: Most if/else tests include the operators < (is less than), > (is greater than), or == (is equal to). In code, the symbol = means "is assigned to", whereas == means "is equal to".

This code asks the user for a secret password and displays a message that depends on their answer.

This code makes a car move back and forth across the screen. It uses if statements to decide when it should turn around.

This code stamps a grid of pigs on the screen. It uses an if statement to figure out when it should start stamping the next row. It uses another if statement to figure out when it's done (it stops looping).