The Ace program shows how to write code that handles a condition. Much of the time, you'll want the program to do one thing if the condition is true, and something else if the condition is false. Most languages include a special variant of the if statement to handle exactly this type of contingency.
The Ace or Not program is built from the Ace program, but it has an important difference, as you can see from Figures 3.5 and 3.6.
In other words, the program does one thing when the condition is true and something else when the condition is false.
The code for the aceOrNot program shows how the else clause can be used to allow for multiple behavior.
<html> <head> <title>Ace or Not</title> </head> <body> <h1>Ace or Not</h1> <h3>Demonstrates if statement with else clause</h3> <? $roll = rand(1,6); print "You rolled a $roll"; print "<br>"; if ($roll == 1){ print "<h1>That's an ace!!!!!</h1>"; } else { print "That's not an ace..."; } // end if print "<br>"; print "<img src = die$roll.jpg>"; ?> <br> Refresh this page in the browser to roll another die. </body> </html>
The interesting part of this code comes near the if statement:
if ($roll == 1){ print "<h1>That's an ace!!!!!</h1>"; } else { print "That's not an ace..."; } // end if
If the condition $roll == 1 is true, the program prints "That's an ace!!!!!" If the condition is not true, the code between else and the end of the if structure is executed instead. Notice the structure and indentation. One chunk of code (between the condition and the else statement, encased in braces) occurs if the condition is true. If the condition is false, the code between else and the end of the if structure (also in braces) is executed. You can put as much code in either segment as you wish. Only one of the segments will run (based on the condition), but you are guaranteed that one will execute.