If Statements
In the previous chapters, you learned all about logical operators and comparison operators. These form the basis for writing boolean expressions in if statements.
We use if statements to run a segment of code only if some boolean expression first evaluates to true. An if statement takes the following basic form:
If the boolean expression evaluates to false, nothing will happen. The code within the if statement is ignored.
If/Else Statements
We can add the else keyword to our if statement. In this case, if the boolean expression in our if statement evaluates to false, the code within the else segment will run. If the boolean expression evaluates to true, the code within the if segment will run.
If/Else/Else If Statements
We can add the else if keyword between our if/else statement. If boolean expression one evaluates to false, then boolean expression two gets evaluated next. If boolean expression two also turns out to be false, the code within the else
segment will run.
You can have as many else if statements as you want. There is no limit!
Test for Negative Numbers
Using if statements, we can determine if a number is negative. If a number is less than 0, we know it is a negative number.
Age Survey
Suppose we want to ask users for their age, but we want to restrict them from being able to enter a negative number. After all, someone can not have a negative age. We can accomplish this by doing the following:
If the user enters a negative age (less than 0), our program informs them that is not allowed. Otherwise, it prints their age back out to them.
Improved Age Survey
We can improve our age survey even further by restricting users from being able to enter ages that are too large. We do this by adding in an else if statement.
With these restrictions, we have created a range of acceptable ages. Valid ages are considered between 0 and 123 inclusive. If a user enters an age that is less than 0, we tell them that is impossible. If a user enters an age over 123, we inform them that no one has ever lived that long before. Otherwise, we simply print their age.
Even or Odd
We want to write a program that tests whether some given number is even or odd. Here is how that can be done.
Recall that the modulus operator %
returns the remainder after a division. For example, let's say the user enters the number 5. 5%2 is equal to 1. Thus, the code within the else
segment will run. It rightly tells us that the number is odd.
Logical Operators in Boolean Expressions
In the previous examples, we have been using comparison operators in our boolean expressions. We will now write a program which combines the usage of comparison operators with logical operators. This program will determine a user's letter grade.
Last updated