0% found this document useful (0 votes)
11 views

Topic 4 - Selection Control Structure

This document discusses selection control structures in programming. It begins by recapping sequential control structures and introducing selection control structures. It then covers one-way selection using the if statement, two-way selection using if-else, logical expressions, and nested if statements. Examples are provided to illustrate how to use selection control structures to make decisions based on conditions. The key points are that selection structures allow executing statements conditionally based on logical expressions, and nested if statements allow multiple levels of conditions.

Uploaded by

syahira Nurwan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Topic 4 - Selection Control Structure

This document discusses selection control structures in programming. It begins by recapping sequential control structures and introducing selection control structures. It then covers one-way selection using the if statement, two-way selection using if-else, logical expressions, and nested if statements. Examples are provided to illustrate how to use selection control structures to make decisions based on conditions. The key points are that selection structures allow executing statements conditionally based on logical expressions, and nested if statements allow multiple levels of conditions.

Uploaded by

syahira Nurwan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

CSC402

PROGRAMMING 1
LECTURE: 04 – SELECTION CONTROL STRUCTURE
2

Learning Objectives:
After completing this chapter, you will be able to:
• describe about control structures
• use relational and logical operators
• form and evaluate logical (Boolean) expressions
• use the selection control structures if, if...else, and switch
in a program
Introduction (Recap)
• We learnt that an algorithm describes the steps
and the order the steps are arranged to solve a
problem.

• At the same time, the order of the steps also


tells the sequence of actions to be carried out/
executed.

• Control structures refers to this sequence of


actions to be carried out/executed.
Control Structures
• There are three control structures in a program which
are sequential, selection and repetition.
• The purpose of the control structure is to control
the execution of statements in the program.
• It is a basic unit of programming logic.
• In mid-1960s, mathematicians proved that any
program, no matter how complicated can be
constructed using only those three basic control
structures.
Sequential Control Structures

• Sequence control structure indicates


instructions are to be executed one statement
at a time in the order they occur from top to
bottom.
• (one line after another) -- like following a
recipe
Sequential Control Structures
The following flowcharts explain each control structure.

crawl

sit

walk

run

Sequential Control Structure


Selection Control Structures
• A selection control structure emphasises on
making a decision or choice based on certain
condition.
• Some statements are executed only if certain
conditions are met.
• A condition is represented by a logical
(Boolean) expression that can be true or false
• A condition is met if it evaluates to true
Selection Control Structures

walk

yes
obstacle stop

no

run

Selection Control Structure


Repetition Control Structures
• The repetition or loop control structure
allows a program to perform the same
process repeatedly. (Next topic)

• A program may combine all three


control structures.
Relational Operators (Recap)
Relational operators:

– Allow comparisons
– Require two operands (binary)
– Return 1 if expression is true, 0 otherwise
Comparing values of different data types may produce unpredictable
results

– For example, 8 < '5' should not be done


Any nonzero value is treated as true
Comparing string Types
• Relational operators can be applied to strings
• Strings are compared character by character,
starting with the first character
• Comparison continues until either a mismatch is
found or all characters are found equal
• If two strings of different lengths are compared
and the comparison is equal to the last character
of the shorter string
− The shorter string is less than the larger string
string Comparison Example

Suppose we have the following declarations:


string str1 = "Hello";
string str2 = "Hi";
string str3 = "Air";
string str4 = "Bill";
Logical (Boolean) Operators (Recap)
Logical (Boolean) operators enable you to combine
logical expressions
Three logical (Boolean) operators:
! - not
&& – and
|| - or
Logical operators take logical values as operands and
yield logical values as results
! is unary; && and || are binary operators
Putting ! in front of a logical expression reverses its
value
Short-Circuit Evaluation
• Short-circuit evaluation: evaluation of a logical
expression stops as soon as the value of the
expression is known

• Example:

(age >= 21) || ( x == 5) //Line 1

(grade == ‘A’) && (x >= 7) //Line 2


Logical (Boolean) Expressions
• The bool Data Type and Logical (Boolean)
Expressions
− The data type bool has logical (Boolean) values
true and false
− bool, true, and false are reserved words
− The identifier true has the value 1
− The identifier false has the value 0
Logical (Boolean) Expressions
(continued)
Logical expressions can be unpredictable
The following expression appears to represent a
comparison of 0, num, and 10:
0 <= num <= 10
It always evaluates true because 0 <= num evaluates
to either 0 or 1, and 0 <= 10 is true and 1 <= 10 is
true
A correct way to write this expression is:
0 <= num && num <= 10
Selection Control Structures
One-Way Selection
One branch of the selection to a “do nothing” branch.
For example:
if it is raining then
take anUmbrella

or

if employee belongs to dentalPlan then


deduct RM40 from employeeGrosspay
One-Way Selection

no yes
raining?

take an
Umbrella
One-Way (if) Selection
One-Way (if) Selection
One-Way (if) Selection

testScore true
greater than or
equal to 80

cout<< "You are an A student";


false
One-Way (if) Selection
int testScore;

testScore = //get test score input

if (testScore >= 80)

This statement is executed


cout<<"You are an A student" ); if the testScore is greater
or equals 80.

cout<<“Thank You”;
One-Way (if) Selection
int testScore;

testScore = //get test score input

if (testScore >= 80)

This statement is executed


cout<<"You are an A student" ); if the testScore is greater
or equals 80.

cout<<“Thank You”;
Two-Way Selection
• Algorithm example, while cooking you may decide
the following:
if we have brown sugar then
use brownSugar
else
use whiteSugar
• Similarly, a payroll program might include a
statement such as:
if hoursWorked is more than 40 then
calculate regularPay and overtimePay
else
calculate regularPay
Two-Way (if…else) Selection
Two-way selection takes the form:
if (expression)
statement1
else
statement2
If expression is true, statement1 is executed otherwise statement2
is executed

statement1 and statement2 are any C++ statements


else is a reserved word
Two-Way (if…else) Selection

false testScore true


greater than or
equal to 80

cout<<"You are an A cout<< “Work harder";


student";
Two-Way (if…else) Selection
int testScore;

testScore = //get test score input


if (testScore >= 80) This statement is executed
cout<<"You are an A student" ); if the testScore is greater or
equal 80.

else
This statement is executed
cout<<“Work harder" ); if the testScore is less than
80.
Two-Way (if…else) Selection
Two-Way (if…else) Selection
Compound Statements
Use braces if the <then> or <else> block has multiple
statements.
if (testScore < 70)
{
cout<<"You did not pass“ << endl;
cout<<“Try harder next time“ ; Then Block
}

else
{
cout<<“You did pass“ << endl; Else Block
cout<<“Keep up the good work“;
}
Style Guide
if ( <boolean expression> ) {

}
else { Style 1

}

if ( <boolean expression> )
{

} Style 2
else
{

}
Nested-if Statement
The then and else block of an if statement can contain any valid statements,
including other if statements. An if statement containing another if
statement is called a nested-if statement.

if (testScore >= 70) {//test score >= 70


if (studentAge < 10) {//and age >= 10
cout<<"You did a great job";
else
cout<<“You did pass";
}
} else //test score < 70
cout<<"You did not pass";
}
Control Flow of Nested-if Statement
true inner if
false testScore
greater than or
equal to 70?

false studentAge true


cout<<"You did not
pass"; < 10 ?

cout<<"You did cout<<"You did a


pass"; great job";
Writing a Proper if Control
if (num1 < 0) negativeCount = 0;
if (num2 < 0)
if (num3 < 0)
negativeCount = 3; if (num1 < 0)
else negativeCount++;
negativeCount = 2; if (num2 < 0)
else
if (num3 < 0)
negativeCount++;
negativeCount = 2; if (num3 < 0)
else negativeCount++;
negativeCount = 1;
else
if (num2 < 0)
if (num3 < 0)
negativeCount = 2;
else
negativeCount = 1; The statement
else
if (num3 < 0) negativeCount++;
negativeCount = 1;
else increments the variable by one
negativeCount = 0;
The if…else…if Control
if (score >= 90)
cout<<"Your grade is A";

else if (score >= 80)


Test Score Grade cout<<"Your grade is B";

90 ≤ score A else if (score >= 70)


80 ≤ score < 90 B cout<<"Your grade is C";

70 ≤ score < 80 C else if (score >= 60)


cout<<"Your grade is D";
60 ≤ score < 70 D
score < 60 F else
cout<<"Your grade is F";
Matching else
Are A and B different?

if (x < y) A Both A and B means…


if (x < z)
cout<<"Hello"; if (x < y) {
else if (x < z) {
cout<<"Good bye"; cout<<"Hello";
} else {
cout<<"Good bye";
}
if (x < y) B }
if (x < z)
cout<<"Hello";
else
cout<<"Good bye";
switch Structures
switch structure: alternate to if-else

switch expression is evaluated first

Value of the expression determines which corresponding


action is taken

Expression is sometimes called the selector


switch Structures (continued)

Expression value can be only integral

Its value determines which statement is selected for


execution

A particular case value should appear only once


switch Structures (continued)
One or more statements may follow a case label
Braces are not needed to turn multiple statements into a
single compound statement
The break statement may or may not appear after
each statement
switch, case, break, and default are reserved
words
switch Statement Rules
When value of the expression is matched against a case value,
– Statements execute until break statement is
found or the end of switch structure is
reached
If value of the expression does not match any of the case values
– Statements following the default label
execute If no default label, and if no match,
the entire switch statement is skipped
A break statement causes an immediate exit from the switch structure
switch Statement Example
int gradeLevel;
cout<<“Enter gradeLevel(Freshman-1,Sophomore-2,Junior-3,Senior=4):";

switch (gradeLevel) {
This statement
is executed if th
case 1: cout<<"Go to the Gymnasium"; e gradeLevel is
break; equal to 1.

case 2: cout<<"Go to the Science Auditorium";


break;

case 3: cout<<"Go to Dewan Aspirasi”;


break;
This statement
is executed if th
case 4: cout<<"Go to Dewan Cemara";
e gradeLevel is
break; equal to 4.
}
Syntax for the switch Statement
switch ( <arithmetic expression> ) {
<case label 1> : <case body 1>

<case label n> : <case body n>
}

Arithmetic Expression
switch ( gradeLevel ) {
Case Label case 1: cout<<"Go to the Gymnasium";
break;
Case
case 2: cout<<"Go to the Science Auditorium";
break;
Body
case 3: cout<<"Go to Dewan Aspirasi”;
break;
case 4: cout<<"Go to Dewan Cemara";
break;
}
switch With No break Statements

true
N equal
x = 10;
switch ( N ) { to 1?

case 1: x = 10; false


case 2: x = 20; true
N equal
case 3: x = 30; to 2?
x = 20;

}
false
true
N equal x = 30;
to 3?

false
switch With break Statements
true
N equal
switch ( N ) { to 1?
x = 10;

case 1: x = 10;
false break;
break; true
N equal
case 2: x = 20; to 2?
x = 20;

break;
false break;
case 3: x = 30;
true
break; N equal
to 3? x = 30;
}
false break;
switch With the default Block
switch (ranking) {

case 10:
case 9:
case 8: cout<<"Master";
break;

case 7:
case 6: cout<<"Journeyman";
break;

case 5:
case 4: cout<<"Apprentice";
break;

default: cout<<"Input error: Invalid Data";


break;
}
THANK YOU…

You might also like