Professional Documents
Culture Documents
Lab 5 Decision Making: 5.1 Objectives
Lab 5 Decision Making: 5.1 Objectives
Lab 5 Decision Making: 5.1 Objectives
DECISION MAKING
5.1 OBJECTIVES
In C++ the condition test is done with the help of Boolean expressions. Boolean functions always return
a bool value that is either true or false. The simplest and most common way to construct such an
expression is to use the relational operators.
Note: Type compatibility is an important factor here. Beware of comparing two variables of different
data types. A character should be compared with a character not with an integer.
You might be thinking that the statements of a program can only be executed one after another but it is
not the case every time. A programmer has complete authority to change the flow of his/her program
and of course any time. This can be done by using control structures that serve to control the behavior
of program, like what function it will perform first and when it will terminate/continue under certain
circumstances.
Control Structures
"Statements used to control the flow of execution in a program".
These could be of selection type or iterative. C++ provides three types of selection statements.
THE if STATEMENT
This statement is used when someone has to make a choice to either skip a particular block of code or
execute it. The if keyword is used to execute a statement or block only if a condition is fulfilled. Its
general form is:
if (condition)
statement
Where condition is the expression that is being evaluated. If this condition is true, statement is
executed. If it is false, statement is ignored (not executed) and the
program continues right after this conditional structure.
A block is a group of
statements which are
separated by semicolons
(;) like all C++ statements,
but grouped together in a
block enclosed in braces:
{}
1 if (x == 100)
2 cout << "x is 100";
In case you have more than one statement to execute upon meeting condition, don’t forget to enclose
it into braces like this:
1 if (x == 100)
2 {
3 cout << "x is 100";
4 x++;
5 cout << “After incrementing x is” << x;
6
7 }
where statement1 is executed in case condition is true, and in case it is not, statement2 is
executed.
1 if (x == 100)
2 cout << "x is 100";
3 else
4 cout << "x is not 100";
This prints x is 100, if indeed x has a value of 100, but if it does not, and only if it does not, it
prints x is not 100 instead.
When there are multiple alternatives to implement a decision, the above methods do not work.
Then else-if statement makes things stress-free.
For example:
1 if (x > 0)
2 cout << "x is positive";
3 else if (x < 0)
4 cout << "x is negative";
5 else if (x == 0)
6 cout << "x is 0";
7 else
8 cout << "Invalid input";
Activity:
Write a program which takes the age of a person and categorize them according to the following:
Children: Less than 13
Teens: Less than 20 and more than 12
Adults: Less than 51 more than 19
Seniors: More than 50