1K - views

# chapter 3 SELECTION CONTROL STRUCTURE

Chapter Outline. 1.Boolean . values. 2.Relational . operators. 3.Simple . Boolean expressions. 4.Logical . operators. 5.Compound . Boolean Expressions. . -Precedence . & associativity. 6.Conditions.

Embed :

Download Presentation - The PPT/PDF document " chapter 3 SELECTION CONTROL STRUCTURE" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.

## Presentation on theme: " chapter 3 SELECTION CONTROL STRUCTURE"— Presentation transcript:

Slide1

chapter 3

SELECTION CONTROL STRUCTURE

Slide2

Chapter Outline

1.Boolean

values

2.Relational

operators

3.Simple

Boolean expressions

4.Logical

operators

5.Compound

Boolean Expressions

-Precedence

& associativity

6.Conditions

7.Types

of selection control structure

-One

way selection

-Two

way selection

-Multiple

selection

-

Multiway

selection (nested)

Slide3

At the end of this class, student should be able to:Interpret the concept of relational and logical operatorsDifferentiate between three types of selectionProduce programs using selection controlIntroduce the nested if problem, explain the output based on the various input from the user.Solve a problem using multiway selection

Chapter Outcome

Slide4

Allow flow of program to be altered, depending on one or more Boolean condition.The real intelligence of a computer comes from its ability to make decisions.No matter how complex a digital computer system seems to be, it’s only making simple Boolean decisions: on or off, 1 or 0 TRUE or FALSE.

Boolean Expression

Slide5

Decision in a computer program is made by testing one condition against another.Example: if x<yHere, the condition of x is tested against the condition of y. If x is in fact less than y, the test result is true.However, if the value of x is greater than or equal to the value of y, the test is false.

Boolean Expression

Slide6

To test condition within a program, you will use relational or logical operators to produce Boolean decision (TRUE or FALSE).When decisions are made in a computer program, they are simply the result of a computation in which the final result is either TRUE or FALSE. The value zero (0) is considered to be FALSE by C++. Any positive or negative value is considered to be TRUE. C++ evaluates any non-zero value to be TRUE.

Boolean Expression

Slide7

In order to evaluate a comparison between two expressions we can use the Relational operators. As specified by the ANSI-C++ standard, the result of a relational operation is a boolean value that can only be true or false, according to the result of the comparison. When complex decisions must be coded into an algorithm, it may be necessary to “chain together” a few relational expression that use relational operators. This is done with logical operators (also known as Boolean Operators).

Relational Operators

Slide8

Allow two quantities to be compared.Normally when the expression have 2 operands or identifiers, either same as, not same, small than, bigger than etc.

C++ OperatorMeaning==Equal!=Not equal to<Less than<=Less than or equal to>Greater than>=Greater than or equal to

Relational Operators

Slide9

Example:

Statement(8 == 8) (3 > 7) (5!= 7) (6 >= 4) (9 < 9)

Resultwould return true. would return false. would return true. would return true. would return false.

Simple Boolean Expressions

Slide10

More examples, instead of using only numeric constants, we can use any valid expression, including variables.Suppose that: a=4, b=2 and c=5

StatementResults(a == 4)would return true.(b*c>= a)would return true since (2*5 >= 4)(a+3 > a*b)would return false since (4+3 > 4*2).((c=2) == b)would return true.

Simple Boolean Expressions

Slide11

#include<iostream.h>void main(){ cout<<(3+3 == 6)<<endl; cout<<(‘A’>’B’)<<endl; cout<<(4*10%2-5>25/5+3)<<endl; }OUTPUT:100

Example:

Relational Operators

Slide12

Symbol

Operator

Description&& AND Both condition must be TRUE || OR Either one of the condition must be TRUE ! NOT Reverse condition

In order to evaluate a comparison between two logical expressions we can use the Logical Operators. If you need to test more that one relational expression at a time, it is possible to combine the relational expressions using the logical operators.

Logical Operators

Slide13

First

OperandaSecondOperandbResulta && bResulta || btruetruetruetruetruefalsefalsetruefalsetruefalsetruefalsefalsefalsefalse

Logical Operators

Slide14

#include<iostream.h>void main(){ cout<<((-2<0)&&(5>=10))<<endl; cout<<(((2-4)==2)||(!(3==6)))<<endl; }OUTPUT:01

If you need to test more than one relational expression at a time, it is possible to combine the relational expressions using the logical operators.

Compound Boolean Expression

Slide15

A program is usually not limited to a linear sequence of instructions. During its process it may take decisions or repeat code. To make a decision or control a loop, a program must have conditions to determine its action. A condition is an expression which consists of relational operator and/or combines with logical operator to produce results whether TRUE or FALSE.The program will proceed with an action (instructions given by the programmer) based on the conditions result (TRUE or FALSE)Decision control can be solved using two methods:

if statement – The simples and most common selection structure is the if statement.switch statement- Is the alternative way and if the condition does not involved with relation or logical operator (used for integer numbers and single char only)

Condition Instruction

Slide16

Type of selection control structure for if statements :One way selectionTwo way selectionMultiple selectionMultiway selection (nested if)

Condition Instruction

Slide17

The if statement tests for a particular condition (expressed as a boolean expression) and only executes the following statement(s) if the condition is trueCompare just a selection which is written in a statement of the form: Example 1:

if (boolean-expression) statement;

cin>>score;if (score>=50) cout<<”PASS”;

One Way Selection -

if

Statement

Slide18

An example follows of a fragment of a program which tests if the denominator is not zero before attempting to calculate fraction.If the value of total is 0, the boolean expression above is false and the statement assigning the value of fraction is ignored.

if (total!=0) fraction=counter/total;statement;

One Way Selection -

if

Statement

Slide19

If a sequence of statements is to be executed, this can be done by making a compound statement or block by enclosing the group of statements in braces.Example 2:

if (boolean-expression){ statements;}

if (total !=0){ fraction = counter/total; cout<<”Proportion is =”<<fraction<<endl;}

One Way Selection -

if

Statement

Slide20

#include<iostream.h>void main(){ char answer; cout<<”Do you want to enroll in this course(y=Yes/n=No)?”; cin>>answer; if(answer == ‘y’) { cout<<”You are now in CSC 128 class.\n”; cout<<”Welcome to the IT world!\n”; } if(answer == ‘n’) cout<<”Never mind.You can enroll later.\n”;} }

Example 3:

One Way Selection -

if

Statement

Slide21

Often it is desirable for a program to take one branch if the condition is true and another if it is false.Compare two selection which is written in a statement of the form:Example 1:

if (boolean-expression) statement-1;else statement-2;

cin>>score;if (score>=50) cout<<”PASS ”;else cout<<”FAIL”<<endl;

Two Ways Selection –

If..else

Statement

Slide22

If a sequence of statements is to be executed, this is done by making a compound statement by using braces to enclose the sequence:

if (boolean-expression){ statements;}else{ statements;}

Two Ways Selection

if..else

Statement

Slide23

Example 2:

cin>>score;if (score>=50){ cout<<”CONGRATULATION!”; cout<<”YOU PASSED ”;}else cout<<”FAIL”<<endl;

Two Ways Selection

if..else

Statement

Slide24

Two way selection using OR operator coding

#include<iostream.h>int main(){ char answer; cout<<”Can you play badminton?” cin>>answer; if(answer == ‘Y’ || answer == ‘y’) cout<<”You can join the club.\n”; else cout<<”Try again later.\n”; return 0;} }

Example 3:

Slide25

Compare more than two selections which is written in a statement of the form

if (boolean-expression-1) Statement-1;else if (boolean-expression-2) Statement-2;else Statement-N;

Multiple Selection

Slide26

Example 1:

#include<iostream.h>int main(){ int score; cout<<”Enter your total mark for CSC 128:”; cin>>score; if(score>=80) { cout<<”\nCongratulation!\n”; cout<<”You pass and get an A.\n”; } else if(score>=60) cout<<”You pass and get a B.\n”; else if(score>=50) cout<<”You pass and get a C.\n”; else { cout<<”Sorry\n”; cout<<”You fail\n”; } return 0;} }

Multiple Selection

Slide27

Flow Chart:

if test 1 statement

else if test 2 statement

if Test 1

expression

else if

Test 2 expression

else if

Test n expression

else if test n statement

else statement

Next Statement

true

true

true

false

false

Multiple Selection

Slide28

Multiple Selection

#include<iostream.h>void main(){ int number; cout<<”Enter a number:”; cin>>number; if(number>0) cout<<”positive number”; else if(number == 0) cout<<”zero number”; else cout<<”negative number”;} }

Example 2:

Slide29

Multiple Selection using AND operator coding

Example 3:

#include<iostream.h>

void main()

{

int val1, val2, val3, max;

cout<<”Enter three integers:”;

cin>>val1>>val2>>val3;

if(val1>=val2 && val1>=val3)

max= val1;

else if(val2>=val1 && val2>= val3)

max= val2;

else if(val3>= val1 && val3>= val2)

max= val3;

cout<<”The maximum number is ”<< max<<endl;

}

}

Slide30

Until now you already learn how to write one-way, two-way and many decision using if, if/else and if/else if/else statements respectively.Occasionally a decision has to be made on the value of a variable which has more than two possibilities. This can be done by placing if statements within other if-else constructions. This is commonly known as nesting and a different style of indentation is used to make the multiple-selection functionality much clearer. Additional decision options can be achieved by using nested if statements.A nested if statement is simply an if statement within an if statement.

Nested (

Multiway

) Selection

Slide31

Written in a statement of the form:

if (boolean-expression-1)

if (boolean-expression-1) Statement-1; else Statement-2;else Statement-3;

Nested (

Multiway

) Selection

Slide32

Example: A user enter temperature in degrees of Celsius and then determine if the temperature constitute water, steam or ice. Print “water” if the temperature is greater than 0 and less than 100, print “steam” if the temperature is greater and equal 100 and print “ice” if the temperature is less and equal to 0.

Nested (

Multiway

) Selection

Slide33

ifTemp>0

if

Temp>=100

Print ICE

PRINT

Water

PRINT Steam

true

false

true

false

Nested (

Multiway

) Selection

Slide34

/*program to evaluate temperature whether it is water, steam or ice*/#include<iostream.h>void main(){ double temp; cout<<”Enter temperature in degree Celcius:”; cin>>temp; if(temp>0) { if(temp>=100) cout<<”STEAM\n”; else } cout<<”WATER\n”; else cout<<”ICE\n”;} }

Nested (

Multiway

) Selection

Slide35

Example 2: Nation’s Air force has asked you to write a program to label supersonic aircraft as military or civilian. Your program is to be given the plane’s observed speed in km/h and its estimated length in meters. For planes traveling in excess of 1100km/h, you will label those longer than 52 meters “civilian” and shorter aircraft as “military”. For planes traveling at slower speeds, you will issue an “aircraft type unknown” message.

Nested (

Multiway

) Selection

Slide36

Nested (Multiway) Selection

Slide37

This last category of selection enables the program to select one of many options or cases.Normally we use switch statement to replace if statement if the condition does not involved with relational or logical operator (used for integer numbers and single char only)

switch

Statement

Slide38

The syntax for switch statement is as followed:

switch (selector variable){ case value for case 1: Statement 1; .......; break; //to stop case1 case value for case n: Statement n; .......; break; //to stop case n default: //works as else in switch statement statement; break; //to stop default statement}

switch

Statement

Slide39

Example 1:

switch Statement

#include<iostream.h>

void main()

{

char code_size;

cin>> code_size;

switch (code_size)

{

case ‘s’:

cout<<”Small Size”;

break;

case ‘M’:

cout<<”Medium Size”;

break;

default:

cout<<”Invalid Code”;

break;

}

cout<<”Hope you have identify your size";

}

}

Slide40

Example 2:For more than one options in every cases (example: capital and small letters), the following example can be done.

switch Statement

#include<iostream.h>

void main()

{

char code_size;

cin>> code_size;

switch (code_size)

{

case ‘s’:

case ‘S’:

cout<<”Small Size”;

break;

case ‘M’:

case ‘m’:

cout<<”Medium Size”;

break;

default:

cout<<”Invalid Code”;

break;

}

cout<<”Hope you have identify your size";

}

}

Slide41

Example 3: Using numbers in switch statement

switch Statement

#include<iostream.h>

void main()

{

int num;

cout<<”Enter your faculty level (1/2/3):”;

cin>>num;

switch (num)

{

case 1:

cout<<”You faculty is FKM”;

break;

case 2:

cout<<”You faculty is FKA”;

break;

case 3:

cout<<”You faculty is FSKM”;

break;

default:

cout<<"Invalid level"<<endl;

}

cout<<”Hope you are satisfied with your results!”;

}

}

Slide42

Uses of break statement in switch StatementThe break statement causes the program to proceed to the first statement after the switch structure. Note that the switch control structure is different to the others in that braces are not required around multiple statements.

switch

Statement

Slide43

Error in switch StatementWhat will happen if you do NOT put the ‘break’ statement in every cases?

switch Statement

#include<iostream.h>

void main()

{

{

case ‘A’:

cout<<”Excellent”;

case ‘B’:

cout<<”Average”;

case ‘C’:

cout<<”Poor”;

case ‘F’:

cout<<”Try Again”;

}

cout<<”\nHope you are satisfied with your results!”;

}

}

Slide44

Error in switch StatementThe compiler will return NO errors.But if one of the cases is TRUE and executed, the rest of cases also will be executed.

Enter a letter of grade: BAveragePoorTry AgainHope you are satisfied with your results!

switch

Statement

Slide45

Question 1: Writing a boolean expression

Exercises

Expression

Result

bool

Q1=true, Q2=true, Q3=false;

Q1 || Q2 || Q3

144

<= 12 * 12

int

a=6, b=3, c=5;

i

. a==6&&b<3

ii

. b>=4 || c

==

5

iii

. 5<=a && b>3 || >=5

11 > 5 || 6 < 15 && 7 >= 8

Slide46

Question 2:Show the output for each program segment below

int

m=6;

if (m < 2 * 5)

cout

<<”Win.”;

cout

<<”Lose.”;

int

x=8;

if ( x!= 8)

{

cout

<<”2 0 2 0”<<

endl

;

cout

<<”2 0 1 3”<<

endl

;

}

cout

<<”The End”<<

endl

;

Slide47

Question 2:Show the output for each program segment below

int

x = 8;

if ( x >= 8)

x= x+2;

if ( x >= 10)

x= x-2;

if ( x >= 12)

x= x+2;

else

x=x-2;

Slide48

Question 2:Show the output for each program segment below

int number = 5;if(number>2 && number<= 5) cout<<"first"<<endl; if (number < 7 && 3 > number) cout<< "second"<<endl; if(number<1||number>=number) cout<< "third"<<endl;

Slide49

Question 2:Show the output for each program segment below

Slide50

Question 3 :Write an appropriate C++ statement if. .else statements for each of the following:

If number is greater than 0, display message” Positif Number”, otherwise display message “Negatif Number”.

If gender code ‘F’ or ‘f’, display status “Female” and if gender code ‘M’ or ‘m’, display status “Male” . Otherwise, display “Invalid Code

”.

Slide51

Question 3 :Write an appropriate C++ statement if. .else statements for each of the following:

If a number is even display the message “Number is Even” otherwise display the message “Number is Odd”.

Calculate amount of taxIncome based on the condition: If income up to RM15,000, tax= 0, if income between RM15,001 and RM25,000, tax = 5% and if income over RM25,000, tax = 10%

Slide52

Question 4 Write a C++ program using the information in the table below to identify the IQ level. User has to enter IQ Scores.

Slide53

Question 4 The National Earthquake Center has asked you to write a program implementing the following decision table to characterize an earthquake based on its Richter scale number.

The program accepts the Richter scale value and determines the earthquake characterization from the above table.

Slide54

Slide55

Question 1: Writing a boolean expression

ExpressionResultbool Q1=true, Q2=true, Q3=false; Q1 || Q2 || Q3 1144 <= 12 * 12 1int a=6, b=3, c=5; i. a==6&&b<3 ii. b>=4 || c==5 iii. 5<=a && b>3 || c >=511 > 5 || 6 < 15 && 7 >= 8

0

1

1

1

Slide56

Question 2:Show the output for each program segment below

int

m=6;

if (m < 2 * 5)

cout

<<”Win.”;

cout

<<”Lose.”;

Win.

Lose

int

x=8;

if ( x!= 8)

{

cout

<<”2 0 2 0”<<

endl

;

cout

<<”2 0 1 3”<<

endl

;

}

cout

<<”The End”<<

endl

;

The

End

Slide57

Question 2:Show the output for each program segment below

int

x = 8;

if ( x >= 8)

x= x+2;

if ( x >= 10)

x= x-2;

if ( x >= 12)

x= x+2;

else

x=x-2;

6

Slide58

Question 2:Show the output for each program segment below

&&&&----int number = 5;if(number>2 && number<= 5) cout<<"first"<<endl; if (number < 7 && 3 > number) cout<< "second"<<endl; if(number<1||number>=number) cout<< "third"<<endl; first third

Slide59

Question 2:Show the output for each program segment below

TWOTHREEFOUR

Slide60

Question 3 :Write an appropriate C++ statement if. .else statements for each of the following:

If number is greater than 0, display message” Positif Number”, otherwise display message “Negatif Number”.

if (number

> 0 )

cout<<“Positif Number”;

else

cout<<“Negatif Number”;

If gender code ‘F’ or ‘f’, display status “Female” and if gender code ‘M’ or ‘m’, display status “Male” . Otherwise, display “Invalid Code

”.

if (gender == ‘F’ || gender == ‘f’)

cout<<“Female”;

else if (gender ==‘M’ || gender ==‘m’)

cout

<<“Male’;

else

cout

<<“Invalid Code “;

Slide61

Question 3 :Write an appropriate C++ statement if. .else statements for each of the following:

If a number is even display the message “Number is Even” otherwise display the message “Number is Odd”.

if (number % 2 == 0)

cout<<“Number is Even”;

else

cout<<“Number

is Odd”;

Calculate amount of taxIncome based on the condition: If income up to RM15,000, tax= 0, if income between RM15,001 and RM25,000, tax = 5% and if income over RM25,000, tax = 10%

if (income <= 15000)

tax = 0;

else if (income > 15001 && income

<=25000)

tax = 0.05;

else

tax = 0.10;

taxIncome = tax * income;

Slide62

Question 4 Write a C++ program using the information in the table below to identify the IQ level. User has to enter IQ Scores.

Slide63

#include <iostream.h>

void main()

{

int score;

cout<<"Enter the IQ Level : ";

cin>>score;

if (score< 20)

cout<<"Slow\n";

else if (score <=140)

cout<<"Normal \n";

else if (score <=210)

cout<<"Intelligent\n";

else

cout<<"Genius \n";

}

Slide64

Question 4 The National Earthquake Center has asked you to write a program implementing the following decision table to characterize an earthquake based on its Richter scale number.

The program accepts the Richter scale value and determines the earthquake characterization from the above table.

Slide65

#include <iostream.h>void main(){ double scale; cout<<"Enter Richter Scale Number : "; cin>>scale; if (scale < 5.0) cout<<"Little or no damage\n"; else if (scale <5.5) cout<<"Some damage \n"; else if (scale <6.5) cout<<"Serious damage: wall may crack or fall \n"; else if (scale<7.5) cout<<"Disaster: houses and building may collapse\n"; else cout<<"Catastrophe: most buildings destroyed \n";}

Slide66

#include <iostream.h>#include<string.h>void main(){ double scale; char status [50]; cout<<"Enter Richter Scale Number : "; cin>>scale; if (scale < 5.0) strcpy (status,"Little or no damage"); else if (scale <5.5) strcpy (status,"Some damage"); else if (scale <6.5) strcpy (status,"Serious damage: wall may crack or fall"); else if (scale<7.5) strcpy (status,"Disaster: houses and building may collapse"); else strcpy (status,"Catastrophe: most buildings destroyed"); cout<<status<<endl;}

Slide67

Question 5Tracethe output for the progam given:

int p=10, q=5,r=10;

if (p>q && p<=r)

p = p + 1;

else

r = r + 1;

cout<<p<<" "<<r<<endl;

11 10

int number = 5;

if(number>2 && number<= 5)

cout<<"first"<<endl;

if (number < 7 && 3 > number)

cout<< "second"<<endl;

if(number<1||number>=number)

cout<< "third"<<endl;

first

third

Slide68

TWOTHREEFOUR

Slide69

THANK YOU