0% found this document useful (0 votes)
18 views53 pages

LESSON 5 Making Decision

Decided

Uploaded by

Ajay Carandan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views53 pages

LESSON 5 Making Decision

Decided

Uploaded by

Ajay Carandan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

LESSON V:

Making Decisions
Topics:

 5.1 Relational Operators


 5.2 The if statement
 5.3 The if/else statement
 5.4 Nested if statements
 5.5 The if/else if statement
 5.6 The Logical Operators
 5.7 The Switch statement
5.1Relational Operators

Relational operators allows you to compare numeric and char values and determine whether one is greater
than, less than, equal to, or not equal to another.

So far, the programs you have written follow this simple


scheme:
• Gather input from the user.
• Perform one or more calculations.
• Display the results on the screen.
5.1Relational Operators

Computers are good at performing calculations, but they


are also quite adapt at comparing values to determine if one
is greater than, less than, or equal to the other. These types of
operations are valuable for tasks such as examining sales
figures, determining profit and loss, checking a number to
ensure it is within an acceptable range, and validating the
input given by a user.
5.1Relational Operators

Numeric data is compared in C++ by using relational


operators. Each relational operator determines whether a
specific relationship exists between two values. For example,
the greater-than operator (>) determines if a value is greater
than another. The equality operator (==) determines if two
values are equal.
5.1Relational Operators

The table below lists all of C++’s relational operators.


5.1Relational Operators

All of the relational operators are binary, which means they use
two operands. Here is an example of an expression using the
greater-than operator:
x > y

This expression is called a relational expression. It is used to


determine whether x is greater than y. The following expression
determines whether x is less than y:
x < y
5.1Relational Operators

The table below shows examples of several relational expressions that compare the
variables x and y.
5.1Relational Operators

THE VALUE OF A RELATIONSHIP

So, how are relational expressions used in a program?


Remember, all expressions have a value. Relational expressions
are also known as Boolean expressions, which means their
value can only be true or false. If x is greater than y, the
expression x > y will be true, while the expression y == x will be
false.
5.1Relational Operators

The == operator determines whether the operand on its left is


equal to the operand on its right. If both operands have the
same value, the expression is true. Assuming that a is 4, the
following expression is true:
a == 4 WARNING! Notice the equality operator is two = symbols
together. Don't confuse this operator with the
assignment operator, which is one = symbol. The
But the following is false: == operator determines whether a variable is
equal to another value, but the = operator
a == 2 assigns the value on the operator's right to the
variable on its left.
5.1Relational Operators

A couple of the relational operators actually test for two


relationships. The >= operator determines whether the operand
on its left is greater than or equal to the operand on the right.
Assuming that a is 4, b is 6, and c is 4, both of the following
expressions are true:
b >= a
a >= c

But the following is false:


a >= 5
5.1Relational Operators

The <= operator determines whether the operand on its left is


less than or equal to the operand on its right. Once again,
assuming that a is 4, b is 6, and c is 4, both of the following
expressions are true:
a <= c
b <= 10

But the following is false:


b <= a
5.1Relational Operators

The last relational operator is != , which is the not-equal operator. It


determines whether the operand on its left is not equal to the operand on
its right, which is the opposite of the == operator. As before, assuming a is
4, b is 6, and c is 4, both of the following expressions
are true:
a != b
b != c

These expressions are true because a is not equal to b and b is not equal
to c. But the following expression is false because a is equal to c:
a != c
5.1Relational Operators

To illustrate this more fully, look at Program 5-1

Program 5-1 These statements may seem odd because


they are assigning the value of a comparison
to a variable. In line 10 the variable trueValue
NOTE: Relational expressions have a is being assigned the result of x < y. Since x is
higher precedence than the
less than y, the expression is true, and the
assignment operator. In the
statement z = x < y; the variable trueValue is assigned the value 1. In
expression x < y is evaluated line 11 the expression y == x is false, so the
first, and then its value is variable falseValue is set to 0.
assigned to z.
5.2 The if statement

The if statement can cause other statements to execute only under


certain conditions.

You might think of the statements in a procedural program as


individual steps taken as you are walking down a road. To reach the
destination, you must start at the beginning and take each step, one
after the other, until you reach the destination. The programs you have
written so far are like a “path” of execution for the program to follow.
5.2 The if statement

The type of code in the picture is


called a sequence structure because the
statements are executed in sequence,
without branching off in another
Instruction. Programs often need more
than one path of execution, however.
Many algorithms require a program to
execute some statements only under
certain circumstances. This can be
accomplished with a decision structure.
5.2 The if statement

In the flowchart, the action “Wear a coat” is


performed only when it is cold outside. If it is not cold
outside, the action is skipped. The action is conditionally
executed because it is performed only when a certain
condition (cold outside) exists.
5.2 The if statement

Another flowchart, where three actions are taken only when


it is cold outside. We perform mental tests like these every
day.
5.2 The if statement

Example 1 Example 2
if (it is raining) if (you have a test tomorrow)
wear a rain coat study tonight
bring an umbrella
else
watch a movie

In this example, the portion in parentheses, called the condition, specifies the
decision you are making and is phrased so that it results in either a true or false answer
only.
If the condition is true, you will perform a specific set of tasks. If the condition is
false, on the other hand, you might not need to perform a different set of tasks.
5.2 The if statement

Example 1 Example 2
if (it is raining) if (you have a test tomorrow)
wear a rain coat study tonight
bring an umbrella
else
watch a movie

For instance, look at the first example, if it is raining (a true condition), then you
will wear a raincoat and bring an umbrella. Notice that you do not have anything in
particular to do if it is not raining (a false condition).
5.2 The if statement

Example 1 Example 2
if (it is raining) if (you have a test tomorrow)
wear a rain coat study tonight
bring an umbrella
else
watch a movie

Compare this with the second example, if you have a test tomorrow (a true
condition), then you will study tonight. If you do not have a test tomorrow (a false
condition), however, you will watch a movie.
5.2 The if statement

One way to code a decision structure in C++ is with the if statement. Here is the general
format of the if statement:

The if statement is simple in the way it works: If the value of the expression inside the
parentheses is true, the very next statement is executed. Otherwise, it is skipped. The
statement is conditionally executed because it only executes under the condition that the
expression in the parentheses is true.

Program 5-2 Program 5-3


5.3 The if else statement

The if/else statement will execute one group of statements if the expression is true, or another
group of statements if the expression is false.

The if/else statement is an expansion of the if statement. Here is its format:

As with the if statement, an expression is evaluated. If the expression is true, a statement or block
of statements is executed. If the expression is false, however, a separate group of statements is
executed.

Program 5-4
5.3 The if else statement

The else part at the end of the if statement specifies a statement that is to be executed
when the expression is false. When number % 2 does not equal 0, a message is printed indicating
the number is odd. Note that the program will only take one of the two paths in the if/else
statement. If you think of the statements in a computer program as steps taken down a road,
consider the if/else statement as a fork in the road. Instead of being a momentary detour, like
an if statement, the if/else statement causes program execution to follow one of two exclusive
paths. The flowchart in picture below shows the logic of this if/else statement.

Notice the programming style used to construct the


if/else statement. The word else is at the same level
of indention as if. The statement whose execution is
controlled by else is indented one level. This visually
depicts the two paths of execution that may be
followed.
5.4 Nested if statements

To test more than one condition, an if statement can be nested inside another if statement.

Sometimes an if statement must be nested inside


another if statement. For example, consider a banking
program that determines whether a bank customer
qualifies for a special, low interest rate on a loan. To
qualify, two conditions must exist: (1) the customer
must be currently employed, and (2) the customer
must have recently graduated from college (in the past
two years). The picture shows a flowchart for an
algorithm that could be used in such a program.
5.4 Nested if statements

To test more than one condition, an if statement can be nested inside another if statement.

If we follow the flow of execution in the flowchart, we


see that the expression employed == 'Y' is tested. If this
expression is false, there is no need to perform further
tests; we know that the customer does not qualify for
the special interest rate. If the expression is true,
however, we need to test the second condition. This is
done with a nested decision structure that tests the
expression recentGrad == 'Y' . If this expression is true,
then the customer qualifies for the special interest rate.
If this expression is false, then the customer does not
qualify. Program 5-6 shows the code for the complete
program.
5.4 Nested if statements
Don’t write the
PROGRAMMING STYLE AND NESTED DECISION STRUCTURES !
if (employed == 'Y') code like this!
{
For readability and easier debugging, it’s if (recentGrad == 'Y') // Nested if
important to use proper alignment and {
cout << "You qualify for the special ";
indentation in a set of nested if statements. cout << "interest rate.\n";
}
This makes it easier to see which actions are else // Not a recent grad, but employed
performed by each part of the decision {
cout << "You must have graduated from ";
structure. For example, the following code is cout << "college in the past two\n";
functionally equivalent to lines 21 through 38 in cout << "years to qualify.\n";
}
Program 5-7. Although this code is logically }
else // Not employed
correct, it is very difficult to read and would be {
very difficult to debug because it is not properly cout << "You must be employed to qualify.\n";
}
indented.
5.4 Nested if statements

PROGRAMMING STYLE AND NESTED DECISION STRUCTURES

Proper indentation and


alignment also makes it easier to see
which if and else clauses belong
together.
5.5 The if/else if statement

The if/else if statement tests a series of conditions. It is often simpler to test a series of conditions with the if/else if
statement than with a set of nested if/else statements.

In C++, and many other languages, you can alternatively test a series of conditions using the if/else
if statement. The if/else if statement makes certain types of nested decision logic simpler to write. Here
is the general format of the if/else if statement:
5.5 The if/else if statement

When the statement executes, expression_1 is


tested. If expression_1 is true, the block of
statements that immediately follows is executed,
and the rest of the structure is ignored. If
expression_1 is false, however, the program jumps to
the very next else if clause and tests expression_2. If
it is true, the block of statements that immediately
follows is executed, and then the rest of the
structure is ignored. This process continues, from
the top of the structure to the bottom, until one of
the expressions is found to be true. If none of the
expressions are true, the last else clause takes over,
and the block of statements immediately following it
is executed.
5.5 The if/else if statement

The last else clause, which does not have an if


statement following it, is referred to as the trailing else.
The trailing else is optional, but in most cases you will use
it.

NOTE: The general format shows braces surrounding


each block of conditionally executed
statements. As with other forms of the if
statement, the braces are required only
when more than one statement is
conditionally executed.

Program 5-8
5.6 The Logical Operators

Logical operators connect two or more relational expressions


into one or reverse the logic of an expression.

In the previous section you saw how a program tests two


conditions with two if statements. In this section you will see how to
use logical operators to combine two or more relational expressions
into one.
5.6 The Logical Operators

In the table below lists C++’s logical operators.


5.6 The Logical Operators

THE && OPERATOR

The && operator is known as the logical AND operator. It takes two expressions as
operands and creates an expression that is true only when both sub-expressions are
true.

Here is an example of an if statement that uses the && operator:

if (temperature < 20 && minutes > 12)


cout << "The temperature is in the danger zone.";
5.6 The Logical Operators

THE && OPERATOR


if (temperature < 20 && minutes > 12)
cout << "The temperature is in the danger zone.";

In the statement above the two relational expressions are


combined into a single expression. The cout statement will only be
executed if temperature is less than 20 AND minutes is greater than
12. If either relational test is false, the entire expression is false, and
the cout statement is not executed.
5.6 The Logical Operators

THE && OPERATOR

NOTE: You must provide complete expressions on both sides of the &&
operator. For example, the following is not correct because the
condition on the right side of the && operator is not a complete
expression.
temperature > 0 && < 100
The expression must be rewritten as
temperature > 0 && temperature < 100
5.6 The Logical Operators

THE && OPERATOR


The table below shows a truth table for the && operator. The truth table lists all the possible
combinations of values that two expressions may have, and the resulting value returned by the
&& operator connecting the two expressions.

As the table shows, both sub-expressions must be true for the && operator to return a true
value.
5.6 The Logical Operators

THE && OPERATOR

NOTE: If the sub-expression on the left side of an && operator is false, the
expression on the right side will not be checked. Since the entire
expression is false if only one of the sub-expressions is false, it would
waste CPU time to check the remaining expression. This is called short
circuit evaluation.

The && operator can be used to simplify programs that otherwise would use nested if
statements.

Program Example
5.6 The Logical Operators

THE || OPERATOR

The || operator is known as the logical OR operator. It takes two


expressions as operands and creates an expression that is true when
either of the sub-expressions are true.

Here is an example of an if statement that uses the || operator:

if (temperature < 20 || temperature > 100)


cout << "The temperature is in the danger zone.";
5.6 The Logical Operators

THE || OPERATOR

if (temperature < 20 || temperature > 100)


cout << "The temperature is in the danger zone.";

The cout statement will be executed if temperature is less than 20 OR


temperature is greater than 100. If either relational test is true, the entire expression is
true and the cout statement is executed.
5.6 The Logical Operators

THE || OPERATOR

NOTE: You must provide complete expressions on both sides of the ||


operator. For example, the following is not correct because the
condition on the right side of the || operator is not a complete
expression.
temperature < 0 || > 100
The expression must be rewritten as
temperature < 0 || temperature > 100
Program 5-9
5.6 The Logical Operators

THE || OPERATOR
The table below shows a truth table for the || operator.

All it takes for an OR expression to be true is for one of the sub-expressions to be true. It
doesn’t matter if the other sub-expression is false or true.
5.6 The Logical Operators

THE || OPERATOR

NOTE: The || operator also performs short circuit evaluation. If the sub-
expression on the left side of an || operator is true, the expression
on the right side will not be checked. Since it’s only necessary for one
of the sub-expressions to be true, it would waste CPU time to check
the remaining expression.

Program 5-10
5.6 The Logical Operators

THE ! OPERATOR
The ! operator performs a logical NOT operation. It takes an operand and
reverses its truth or falsehood. In other words, if the expression is true, the ! operator
returns false, and if the expression is false, it returns true. Here is an if statement using
the ! operator:

if (!(temperature > 100))


cout << "You are below the maximum temperature.\n";
5.6 The Logical Operators

THE ! OPERATOR
if (!(temperature > 100))
cout << "You are below the maximum temperature.\n";

First, the expression (temperature > 100) is tested to be true or false. Then the !
operator is applied to that value. If the expression (temperature > 100) is true, the !
operator returns false. If it is false, the ! operator returns true. In the example, it is
equivalent to asking “is the temperature not greater than 100?”
5.6 The Logical Operators

THE ! OPERATOR
The table below shows a truth table for the ! operator.

Program 5-11
5.7 The Switch statement

The switch statement lets the value of a variable or expression


determine where the program will branch.
A branch occurs when one part of a program causes another part
to execute. The if/else if statement allows your program to branch into
one of several possible paths. It performs a series of tests (usually
relational) and branches when one of these tests is true. The switch
statement is a similar mechanism. It, however, tests the value of an
integer expression and then uses that value to determine which set of
statements to branch to.
5.7 The Switch statement

Here is the format of the switch statement:

The first line of the statement starts with


the word switch, followed by an integer
expression inside parentheses. This can be either
of the following:
 a variable of any of the integer data types
(including char )
 an expression whose value is of any of the
integer data types
5.7 The Switch statement

Here is the format of the switch statement:

On the next line is the beginning of a


block containing several case statements. Each
case statement is formatted in the following
manner:
case ConstantExpression :
// place one or more
// statements here
5.7 The Switch statement

After the word case is a constant expression (which must be of an integer type),
followed by a colon. The constant expression may be an integer literal or an integer
named constant. The case statement marks the beginning of a section of statements. The
program branches to these statements if the value of the switch expression matches that
of the case expression.
WARNING! The expression of each case statement in the block
! must be unique.
NOTE: The expression following the word case must be an
integer literal or constant. It cannot be a variable,
and it cannot be an expression such as x < 22 or
n == 50.
An optional default section comes after all the case statements. The program branches to this
section if none of the case expressions match the switch expression. So, it functions like a trailing else in
an if/else if statement.
5.7 The Switch statement

Notice the break statements that are in the case 'A' ,


Program 5-12 case 'B' , and case 'C' sections.

The case statements show the program where to start executing in the block and the
break statements show the program where to stop. Without the break statements, the program
would execute all of the lines from the matching case statement to the end of the block.
5.7 The Switch statement

NOTE: The default section (or the last case section, if there is no
default) does not need a break statement. Some
programmers prefer to put one there anyway, for
consistency.
Program 5-13 Without the break statement, the program “falls
through” all of the statements below the one with
the matching case expression. Sometimes this is what
you want.

The program uses a switch statement with carefully Program 5-14


omitted break s to print the features of the selected
model.
5.7 The Switch statement

The available choices are A, B, and C. The switch


Program 5-15 statement will recognize either upper or lowercase
letters.

When the user enters 'a' the corresponding case has no statements associated with it,
so the program falls through to the next case , which corresponds with 'A'.
case 'a':
case 'A': cout << "30 cents per pound.\n";
break;
The same technique is used for 'b' and 'c'.

You might also like