Professional Documents
Culture Documents
4 [CLO-3]
Purpose 1. Understand the purpose of decision making statements.
2. Usage of IF and Switch statement.
3. Solving problem using decision making statements.
There are two versions of the if statement, called if–then–else and if–then. We
If Statement: begin with the first version. Suppose we wish to enter a student’s test score and
print out the message You did not pass if the score is less than 70 and You did
pass if the score is 70 or higher. Here’s how we express this logic in Java:
Relational operators:
The six relational operators we can use in conditional expressions are:
<
<= // less than
// less than or equal to
== // equal to
// not equal to
!= // greater than
> // greater than or equal to
>=
Here are some more examples:
a * a <= c //true if a * a is less than or equal to c
x + y != z //true if x + y is not equal to z
a == b //true if a is equal to b
If the boolean expression evaluates to true, then the statements in the <then
block> are executed. Otherwise, the statements in the <else block> are executed.
We will cover more complex boolean expressions in Section 5.2. Notice that we
can reverse the relational operator and switch the then and else blocks to derive
the equivalent code.
Nested If The then and else blocks of an if statement can contain any statement including
Statements: another if statement. An if statement that contains another if statement in either its
then or else block is called a nested if statement. Let’s look at an example. In the
earlier example, we printed out the messages You did pass or You did not pass
depending on the test score. Let’s modify the code to print out three possible
messages. If the test score is lower than 70, then we print You did not pass, as
before. If the test score is 70 or higher, then we will check the student’s age. If the
age is less than 10, we will print You did a great job. Otherwise, we will print
You did pass, as before. Figure 5.4 is a diagram showing the logic of this nested
test. The code is written as follows:
1. Write an if statement to find the smallest of three given integers without using the min method of
the Math class
2. Write an if statement that prints out a message based on the following rules:
4. Employees at Lo-Fat Burgers earn the basic hourly wage of $7.25. In addition, they will receive a
commission on the sales they generate while tending the counter. The commission is based on the
following formula: