You are on page 1of 37

Lecture 12:

Control Structures:
Selection/ Branch/Conditional

1
Lecture 12 Objectives

In this lecture, we wil learn:

• How to use selection structures in a C++


program (discussed in Lecture 6)

• How to use if and if/else constructs to


execute a group of statements.

• To trace an algorithm or program to verify the


expected result.
Lecture 12 Contents

12.1 Introduction
12.2 Logical Data and Operators
12.3 Single-Selection: if
12.4 Double-Selection: if...else
12.5 Summary
Lecture 12 12.1 Introduction

• Selection is one of the important programming


constructs.

• Since computer programs are used to solve real-world


problems, decision making is an important part.

• How are decisions made by a computer?


• Checking if a condition or a set of conditions is True (1) or
false (0) and executing commands accordingly.

• Complex decisions to be reduced to simple decisions


that the computer can handle  programming logic.

_____________________________________________________________________________________________________________________
I
Forouzan, B.A. and Gilberg, R.F (2001). Computer Science: A Structured Programming Approach Using C (2/E). United State of America: Brook/Cole.
Lecture 12 12.1 Introduction

• The selection structure is chosen based on requirements.

• In C++, there are three selection structures:


• if, if/else, if/else if, can be expanded using
nesting or stacking
• conditional operators
• switch, case and break

_____________________________________________________________________________________________________________________
I
Forouzan, B.A. and Gilberg, R.F (2001). Computer Science: A Structured Programming Approach Using C (2/E). United State of America: Brook/Cole.
Lecture 12 12.1 Introduction

Re
c al
• In Lecture 6, control structures were l
discussed in the context of Pseudo-code
and Flowcharts.

Control
Structures

Sequential Selective Repetition


Structure Structure Structure

Multiple-
Single-
Double-Selection Selectio
Selection
n
if if...else switch
____________________________________________________________________________________________________________________________________
I
Radzi, N.H.M, Hashim, S.Z.M. and Samsuri, P. (2001). Pengaturcaraan C. Malaysia: McGraw-Hill.
2
Deitel, H.M. and Deitel, P.J (2013). C How to Program 7/E. United State of America: Pearson Education
Lecture 12 Contents

12.1 Introduction
12.2 Logical Data and Operators
• Logical data in C++
• Logical operators
• Evaluating logical expressions
• Relational operators
12.3 Single-Selection: if
12.4 Double-Selection: if...else
12.5 Summary
Lecture 12 12.2 Logical Data and Operators
Introduction

• A data or expression is called logical if it conveys the idea


of true or false.

• In real life, logical data are created as answers to the


questions that have a yes-no answer.

• For a computer, we use true or false

_____________________________________________________________________________________________________________________
I
Forouzan, B.A. and Gilberg, R.F (2001). Computer Science: A Structured Programming Approach Using C (2/E). United State of America: Brook/Cole.
Lecture 12 12.2 Logical Data and Operators
Logical data in C++

• Called bool (Boolean).


• A Zero value is treated as false
• A Non-Zero value is treated as true

Figure: True and False in arithmetic scale

_____________________________________________________________________________________________________________________
I
Forouzan, B.A. and Gilberg, R.F (2001). Computer Science: A Structured Programming Approach Using C (2/E). United State of America: Brook/Cole.
Lecture 12 12.2 Logical Data and Operators
The flag

• Variable that signals a condition being true or false.


• bool data type
• As with other variables, it’s a good programming practice to
assign an initial value.

• Recall C++’s convention of using zero and nonzero values


to represent false and true
• the value 0 in a condition evaluates to false,
• while any nonzero value evaluates to true.

• Assigning any non-zero value to a bool variable sets it to 1.

_____________________________________________________________________________________________________________________
I
Deitel, H.M. and Deitel, P.J (2013). C How to Program 7/E. United State of America: Pearson Education.
Lecture 12 12.2 Logical Data and Operators
Relational operators
• Used to compare numbers to determine relative order
• Relational expressions produce true or false as output
• Operators:

• The first 4 operators (<, <=, >, >=) have a higher


precedence.

____________________________________________________________________________________________________________________________
I
Forouzan, B.A. and Gilberg, R.F (2001). Computer Science: A Structured Programming Approach Using C (2/E). United State of America: Brook/Cole.
Lecture 12 12.2 Logical Data and Operators
Relational Operators Example

int main()
{ int num;
cout<<"Enter number: ";
cin>>num;

cout<<"\nNumber < 100: "<<(num<100);


cout<<"\nNumber > 100: "<<(num>100);
cout<<"\nNumber = 100: "<<(num==100);
cout<<"\nNumber !=100: "<<(num!=100);

return 0;
}
_____________________________________________________________________________________________________________________
I
Deitel, H.M. and Deitel, P.J (2013). C How to Program 7/E. United State of America: Pearson Education.
Lecture 12 12.2 Logical Data and Operators

• It is important to recognize that each operator is a


complement of another operator in the group.

Figure: Logical operators complements


____________________________________________________________________________________________________________________________
I
Forouzan, B.A. and Gilberg, R.F (2001). Computer Science: A Structured Programming Approach Using C (2/E). United State of America: Brook/Cole.
Lecture 12 12.2 Logical Data and Operators

• If we want to simplify an expression involving the not (!)


and the less than (<) operator, we use the greater than or
equal (>=) .

Original Expression Simplified Expression

!(x < y) x >= y


!(x > y) x <= y
!(x != y) x == y
!(x <= y) x > y
!(x >= y) x < y
!(x == y) x != y
Figure:_____________________________________________________________________________________________________________________________
Examples of relational operator complements
I
Forouzan, B.A. and Gilberg, R.F (2001). Computer Science: A Structured Programming Approach Using C (2/E). United State of America: Brook/Cole.
Lecture 12 12.2 Logical Data and Operators
Logical operators

• Used to write complex expressions using simpler ones


• Operators, meaning, and explanation:

&& AND New relational expression is true if both


expressions are true
|| OR New relational expression is true if either
expression is true
! NOT Reverses the value of an expression –
true expression becomes false, and false
becomes true

_____________________________________________________________________________________________________________________
I
Forouzan, B.A. and Gilberg, R.F (2001). Computer Science: A Structured Programming Approach Using C (2/E). United State of America: Brook/Cole.
Lecture 12 12.2 Logical Data and Operators

• ! has highest precedence among these, followed by &&,


then ||

• If the value of an expression can be determined by


evaluating just the sub-expression on left side of a logical
operator, then the sub-expression on the right side will
not be evaluated (short circuit evaluation)

_____________________________________________________________________________________________________________________
I
Forouzan, B.A. and Gilberg, R.F (2001). Computer Science: A Structured Programming Approach Using C (2/E). United State of America: Brook/Cole.
Lecture 12 12.2 Logical Data and Operators

Figure: Logical operators truth table


_____________________________________________________________________________________________________________________
I
Forouzan, B.A. and Gilberg, R.F (2001). Computer Science: A Structured Programming Approach Using C (2/E). United State of America: Brook/Cole.
Lecture 12 12.2 Logical Data and Operators
Evaluating logical expressions

• Computer languages can use two methods to evaluate


the binary logical relationships.

1) The expression must be completely evaluated


before result is determined.

2) Sets the resulting value as soon as it is known.

false && (anything) true || (anything)

false true

Figure: Short-circuit methods for and/or


_____________________________________________________________________________________________________________________
I
Forouzan, B.A. and Gilberg, R.F (2001). Computer Science: A Structured Programming Approach Using C (2/E). United State of America: Brook/Cole.
Lecture 12 Contents

12.1 Introduction
12.2 Logical Data and Operators
12.3 Single-Selection: if
12.4 Double-Selection: if...else
12.5 Summary
Lecture 12 12.3 Single-Selection: if
The if statement
• Allows statements to be conditionally executed or skipped
over.

• Models the way we mentally evaluate situations:


"If it is raining, take along an umbrella"
"If it is cold outside, wear a coat”
“If you don’t understand, ask someone”
Lecture 12 12.3 Single-Selection: if

"If it is cold outside, "If it is cold outside,


wear a coat” wear a coat, a hat, gloves”

Figure: Flowchart for evaluating a decision


Lecture 12 12.3 Single-Selection: if

C++ Format: Flowchart:


1. if(expression)
statement;

2. if (expression)
{
statement_1;
statement_2;

statement_n;
}

• To evaluate 1:
o If the expression is true, then statement is executed.
o If the expression is false, then statement is skipped.
Lecture 12 12.3 Single-Selection: if
#include <iostream>
Example: if using namespace std;

Print “Passed” if int main ()


{ How the flowchart
the grade on an
will look like?
int grade;
exam is greater or
equal to 60. cout<<“Enter grade:\n”;
cin>>grade;

if (grade>=60)
cout<<“\nPassed”;

return 0;
}

_____________________________________________________________________________________________________________________
I
Deitel, H.M. and Deitel, P.J (2013). C How to Program 7/E. United State of America: Pearson Education.
Lecture 12 12.3 Single-Selection: if

Activity 12.2: Trace the following programs if the input is 10 and 50.
#include <iostream>
using namespace std;

int main () Category A


{
float mark;
bool pass=false;
cout<<“Enter your marks:\n”;
cin>>mark;

if (mark>=30)
pass=true;
if (pass)
cout<<“\nYou passed the test”;
if(!pass)
cout<<“\nYou failed the test”;
return 0;
}
Lecture 12 12.3 Single-Selection: if

Solution 12.2:
Lecture 12 12.3 Single-Selection: if

Activity 12.1: The domestic electricity usage will be charged with


basic rate PKR20 per kWh. Calculate the bill by
asking the user for consumed kWh. Print the total
amount bill and if it is less than or equal to PKR200,
print “Your bill is waived off”.

a) Draw the flowchart for the problem.


b) Write a C++ program.
Lecture 12 12.3 Single-Selection: if

Solution 12.1: a) The flowchart for the problem.

Start

Read kWh

Total=kWh*20 Category A

Print Total

True Print “Your


Total<= 200 bill is
waived off”
False

End
Lecture 12 Contents

12.1 Introduction
12.2 Logical Data and Operators
12.3 Single-Selection: if
12.4 Double-Selection: if...else
• Nested if
• Conditional expressions
12.5 Summary
Lecture 12 12.4 Double-selection: if...else
The if...else statement
• Provides two possible paths of execution.

• Performs one statement or block if the expression is true,


otherwise performs another statement or block.

• Flowchart:
Lecture 12 12.4 Double-selection: if...else

• General Format:
if (expression) if (expression)
{ statement1;
statement1; // or block else
} statement2;
else Note: If consists of only
{ one statement, then the
statement2; // or block curly braces may be
} omitted !

To evaluate:
•If the expression is true, then statement1 is executed
and statement2 is skipped.
•If the expression is false, then statement1 is skipped
and statement2 is executed.
Lecture 12 12.4 Double-selection: if...else
Example: Suppose the passing grade on an exam is 60.

• Flowchart:

• Coding: if (grade >= 60)


cout<<“\nPassed”;
else
cout<<“\nFailed”;
____________________________________________________________________________________________________________________________________

____________________________________________________________________________________________________________________________________
I
Deitel, H.M. and Deitel, P.J (2013). C How to Program 7/E. United State of America: Pearson Education.
Lecture 12 12.4 Double-selection: if...else

Condition An expression that is


evaluated to TRUE or
FALSE

if (grade >= 60)


cout<<“\nPassed”;
else
TRUE part
cout<<“\nFailed”;
A block of statements
that are executed if
FALSE part A block of statements
the condition evaluates
that are executed if the
to TRUE
condition evaluates to
FALSE
Chapter 12 12.4 Double-selection: if...else

if (condition)
statement;
Summary of if, if/else constructs:
if (condition)
{ statement_1;
The three forms of if statements. :
:
statement_n; }
•The condition is always in
parentheses. if (condition)
{ statement_1;
:
•All TRUE-parts and all FALSE-parts :
are a single statement or a block of statement_n; }
code / compound statements else
{ statement_1;
:
:
statement_n; }
Lecture 12 12.4 Double-selection: if...else

Activity 12.3: Write a C++ program to calculate the weekly salary of


an employee using his hourly pay rate, and the number
of hours he/she has worked in the week. The salary
calculation works as follows:
Category A
• The base salary is equal to the product of hourly pay
rate and the number of hours he/she worked in the
week, up to 40 hours.
• Additionally, bonus salary is given if the number of
hours is more than 40 in a week. The bonus salary is
equal to 1.5 times the hourly pay rate times the
number of hours exceeding 40.
• For all employees, the total salary is equal to the sum
of base salary and bonus salary.
Lecture 12 12.4 Double-selection: if...else
int main ()
{
float hours,base=0,bonus=0;total=0;
const float rate=1000;
Category A
cout<<“Enter number of hours:\n”;
cin>>hours;

if (hours>40)
{
base=rate*40;
bonus=1.5*rate*(hours-40);
}
else
base=hours*rate;
total=base+bonus;
cout<<“\nWeekly Payroll”;
cout<<“\nBase salary = ”<<base;
cout<<“\nBonus salary = ”<<bonus;
cout<<“\nTotal salary = ”<<total;
return 0;
}
Lecture 12 Contents

12.1 Introduction
12.2 Logical Data and Operators
12.3 Single-Selection: if
12.4 Double-Selection: if...else
12.5 Summary
Lecture 12 12.5 Summary

• Writing C++ programs using Single-selection (if) and


Double-selection (if/else) constructs.

• The algorithm or program may be verified in order to


check the expected result.

You might also like