Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 54

Making Decisions /

Conditional
Statements

TOPICS

Use the if and if-else statements


Use nested if statements
The if else if with trailing else
Avoid common pitfalls with if statements
Use the switch statement
Use the conditional operator
Use the logical AND and OR operators
Make decisions with structure fields

Four Program Structures

Sequence
Decision
Repetition
Case

Decision Structure
Makes a decision and then takes an
appropriate action based on that
decision
Example: waiting or crossing at
railroad tracks depending on signal
lights
Every decision boils down to on or
off, yes or no, 1 or 0.

Using The IF Statement


The Single-Alternative if
One way to use an if is in a singlealternative selection wherein
one in which an action takes place
only when the result of the decision
is true.
It takes the form:
if (Boolean expression)
action/statement if true;

Using The IF Statement


The Single-Alternative if
When you write an if statement, you
use the keyword if, a Boolean
expression within parentheses, and
any statement that is the action that
occurs if Boolean expression is true.

Format of the if
Statement
if (expression)
{
statement1;
statement2;

statementn;
}

No ;
goes here

; goes here

The block inside the braces is called the body


of the if statement.
If there is only 1 statement in the body, the
{ } may be omitted.

How the if Statement


Works
If (expression) is true, then the
statement(s) in the body are
executed.
If (expression) is false, then the
statement(s) are skipped.

Flowchart Diagram of an if
Statement
False

True

Action if true

Example if Statements
if (score >= 60)
cout << "You Passed!!" <<endl;

if (number == 7)
cout<< "It is number 7!!" <<endl;

if Statement Notes
Do not place ; after (expression)
The parentheses surrounding the
evaluated expression in the if
statement are essential
0 is false; any other value is true
Any value other than 0, even a
negative value, is considered to be
true.
Thus, the statement if (-5) cout<<
OK; would display OK.

if Statement Notes
Most frequently, you create an if
statements Boolean expression
using one of the six relational
operators:
>
<
>=
<=
==
!=

Greater than
Less than
Greater than or equal to
Less than or equal to
Equal to
Not equal to

The if/else Statement


The Dual-Alternative if
The dual alternative if, also
called if else structure, takes
one action when its Boolean
expression is evaluated as true, and
uses an else clause to define the
actions to take when the expression
is evaluated as false.

The if/else Statement


The Dual-Alternative if
It takes the form:
if (Boolean expression)
action/statement if true;
else
action/statement if false;

Format of the if-else


Statement
Allows a choice between statements
depending on whether (expression) is
true or false
if (expression)

statement set1;

}
else
{
statement set2;
}

How the if/else Works


If (expression) is true, statement
set 1 is executed and statement
set 2 is skipped.
If (expression) is false, statement
set 1 is skipped and statement set
2 is executed.

Flowchart Diagram of an
if-else Statement
True

statement
set 1

expression

False

statement
set 2

Example if/else
Statements
if (score >= 60)
cout << "You Passed!! <<endl;
else
cout << "You Failed!! <<endl;

Example if/else
Statements
if (genderCode == F)
cout << Female <<endl;
else
cout << Male <<endl;

Example if/else
Statements
Create a C++ program that
compare the age of two persons
and evaluate whose older than
the other.

Example if/else
Statements
if(age1 > age2)
cout << "The first person is older.";
else
cout << "The second person is older.";

Example if/else
Statements
What if the two persons are the same
age?
The program incorrectly says the
second person is older.
To solve this we must handle all three
possibilities.

if/else Statements
The if-else statement allows a
choice to be made between two
possible alternatives.
Sometimes a choice must be made
between more than two possibilities.
Consider using a the if/else if
statement.

The if/else if Statement


Chain of if statements that test in
order until one is found to be true
if/else if also allows a choice of
more than two or many alternatives.

if/else if Format
if (expression)
statement set 1;
else if (expression)
statement set 2;

else if (expression)
statement set n;

Using a Trailing else


Used with if/else if statement
when none of (expression) is true
Provides a default statement or action
Can be used to catch invalid values or
handle other exceptional situations

Example of if/else if
if(age1 == age2)
cout << "They are the same age." <<endl;
else if (age1 > age2)
cout << "The first person is older.";
else
cout << "The second person is older.";

Example of if/else if
if (genderCode == F)
cout << Female <<endl;
else if (genderCode == M)
cout << Male <<endl;
else
cout << Invalid Code;

Example if/else if with


Trailing else
if (age
cout
else if
cout
else if
cout
else
cout

>= 21)
<< "Adult";
(age >= 13)
<< "Teen";
(age >= 2)
<< "Child";
<< "Baby";

Example if/else if with


Trailing else
if (department == 1)
cout << "Human Resources" << endl;
else if (department == 2)
cout << "Sales" << endl;
else if (department == 3)
cout << "Information Systems" <<endl;
else
cout << "No such department" <<endl;

Example if/else if with


Trailing else
if (number < 0)
cout<< "Entered number is a negative
number!!" <<endl;
else if (number>0)
cout<< "Entered number is a positive
number!!" <<endl;
else
cout << "Entered number is zero!!" <<endl;

Knowledge Check
Create a C++ program that
determine if you can vote else youre
not yet eligible to vote.

Avoid Common Pitfalls


with if Statements
Forgetting that C++ comparisons are
case sensitive
Assuming that indentation has a
logical purpose
Adding an unwanted semicolon
Forgetting curly braces
Using = instead of ==
Making unnecessary comparisons

Forgetting that C++


comparisons
are case sensitive

When you make a character


comparison, you must remember that
C++ comparison are case sensitive.
The program genderCode for
instance, the character f is different
from the character F for Female.
Dont be surprised when the program
displays the message Invalid Code.

Assuming that Indentation has


a Logical Purpose, Adding an
Unwanted Semicolon and
Forgetting Curly Braces
Remember that C++ ignore indentation.
Only the placement of semicolons and
curly braces matters in determining
where statements and blocks end.
Ex: if (age1 > age2);
else;

Using = Instead of ==
Dont use a single equal sign when
your intention is to compare values.
Example: if (number = 7) //Notice the
single equal sign: if (number == 7)
if (genderCode == M')

Making Unnecessary
Comparisons
A program that determines whether
the user can vote.
This second if
if (age >= 18)
is unnecessary;
cout << You can vote!an; else would be
more efficient
if (age < 18)
cout << Youre not yet eligible to
vote!;

Making Unnecessary
Comparisons
An if else statement that avoids
the unnecessary comparison
if (age >= 18)
cout << You can vote! ;
else
cout << Youre not yet
eligible to vote!;

The switch Statement


Used to select among statements
from several alternatives
May sometimes be used instead of
if/else if statements

switch Statement Format


switch (expression)
{
case exp1: statement
break;
case exp2: statement
break;
case expn: statement
default:
statement
}

set 1;
set 2;
set n;
set ;

switch Statement
Requirements
1) expression must be a char or an
integer variable or an expression
that evaluates to an integer value
2) exp1 through expn must be constant
integer expressions and must be
unique in the switch statement
3) default is optional but
recommended

How the switch Statement


Works
1) expression is evaluated
2) The value of expression is compared
against exp1 through expn.
3) If expression matches value expi, the
program branches to the statement(s)
following expi and continues to the end of
the switch
4) If no matching value is found, the program
branches to the statement after default:

The break Statement


Used to stop execution in the current
block
Also used to exit a switch statement
Useful to execute a single case
statement without executing
statements following it

Example switch Statement


switch (department)
{
case 1: cout << "Human Resources" <<endl;
break;
case 2: cout << "Sales" <<endl;
break;
case 3: cout << "Information Systems" <<endl;
break;
default:
cout << "No such department" <<endl;
}

Example switch Statement


If you remove the break statements then all
four cout statements (those that display
Human Resources, Sales, Information
Systems and No such department) execute
when the value of department is 1.
The switch statement can contain any number
of cases in any order. The values in the case
statements do not have to occur in descending
order nor do they have to be consecutive.

Example switch Statement


switch (gender)
{
case 'f': cout << "female";
break;
case 'm': cout << "male";
break;
default : cout << "invalid gender";
}

Examples switch Statement


Note
The department variable is declared as
int
While the gender variable is declared
as char
The switch statement is not as flexible
as if; you use it only when you have
several outcomes that depends on the
value of a single variable or expression.

Using switch with a Menu


switch statement is a natural choice
for menu-driven program
display menu
get user input
use user input as expression in switch
statement
use menu choices as exp to test against
in the case statements

Conditional_Exercises
1. Write a C++ program that allows the user to
enter two double values. Display one of two
messages: The first number you entered is
larger., or The second number you entered
is larger. Save the file as LargerOrNot.cpp
2. Write a C++ program that allows the user to
enter two double values. Display one of three
messages: The first number you entered is
larger., The second number you entered is
larger., or The numbers are equal. Save
the file as CompareThree.cpp

Conditional_Exercises
3. Write a program that allows the user
to enter two numeric values. Then let
the user enter a single character as
the desired operation: a for add, s
for subtract, m for multiply, or d for
divide. Perform the arithmetic
operation that the user selects and
display the results. Save the file as
ArithmeticChoice.cpp

Conditional_Exercises
4. Write a program for furniture
company. Ask the user to choose P for
pine, O for oak, or M for mahogany.
Show the price of a table
manufactured with the chosen wood.
Pine table cost $100, oak tables cost
$225 and mahogany tables cost $310.
Save the program as Furniture.cpp

Conditional_Exercises
5. Make and run a program that will input a
character and determine if it is a vowel or a
consonant. Special characters and numbers
are considered Invalid. Save the program
as VowelConsonant.cpp
6. Make and run a program that will
determine the position in the inputted
letter from the alphabet. Special characters
and numbers are considered Invalid. Save
the program as PositionLetter.cpp

That in All
Things,God May Be
Glorified!

Thank you!
Prepared by: Prof. LRQ Natividad

You might also like