Page 67 - Introduction to Programming with Java: A Problem Solving Approach
P. 67
print “The area is ” (3.1416 * radius * radius)
In this case, we put parentheses around the mathematical calculation to emphasize that we want the computer to print the result of the calculation, rather than individual variable values. You can always use parentheses to specify that operations inside the parentheses should be done before operations outside the parentheses.
“if, else”
Now for the second form of the if statement—the “if, else” form. Use the “if, else” form if you want to do either one thing or another thing. Here is its format:
if <condition> <statement(s)>
else
<statement(s)>
And here’s how the “if, else” form of the if statement works:
• If the condition is true, execute all statements subordinate to the “if,” and skip all statements subordi- nate to the “else.”
• If the condition is false, skip all statement(s) subordinate to the “if,” and execute all statements subor- dinate to the “else.”
print “Pass” else
print “Fail”
Note how we indent the print “Pass” statement since it is subordinate to the if condition. Note how we indent the print “Fail” statement since it is subordinate to the “else.”
“if, else if”
The “if, else” form of the if statement addresses situations in which there are exactly two possibilities. But what if there are more than two possibilities? For example, suppose that you want to print one of five pos- sible letter grades for a particular numerical score. You can do it by using the “if, else if” form of the if state- ment to establish parallel paths:
if grade is greater than or equal to 90 print “A”
else if grade is greater than or equal to 80 print “B”
else if grade is greater than or equal to 70 print “C”
else if grade is greater than or equal to 60 print “D”
else
print “F”
Here’s an example that uses the “if, else” form of the if statement: if grade is greater than or equal to 60
Apago PDF Enhancer
2.7 if Statements 33