Topic 3: Selection Control Structure · 2017-10-01 · C++ Programming: From Problem Analysis to...
Transcript of Topic 3: Selection Control Structure · 2017-10-01 · C++ Programming: From Problem Analysis to...
Selection Control Structure
1) Boolean values2) Relational Operators
3) Logical Operators
4) Type of selection control structures
Boolean values
• Boolean values only have two possible values: true (1) and false (0).
• To declare a boolean variable, we use the keyword bool(data type).
• when converting integers to booleans, the integer zero resolves to boolean false, whereas non-zero integers all resolve to true.
bool bValue;
bValue = true;
Relational operators
Relational operator
Relational operators are used to compare two values to form a condition.
Math C++ Plain English
= == equals [example: if(a==b) ]
[ (a=b) means put the value of b into a ]
< < less than
<= less than or equal to
> > greater than
>= greater than or equal to
!= not equal to
Relational operator• 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.
Simple Boolean Expressions
• Example:a) 8 < 15 = true
b) 2.5 >= 5.8 = false
• Exercise:a) 6 != 6
b) 5.9 <= 7.5
Logical operators
Logical operator
• The AND operator will give the value TRUE when all expression are TRUE
• The OR operator will give the value TRUE if any expression is TRUE
• Putting ! in front of a logical expression reverses its value
OPERATOR DESCRIPTION
! Not
&& AND
|| OR
logical operator
• Truth table
1
1
1 1
Precedence of operator
• Precedence of operators (from highest to lowest)– Parentheses ( … )
– Unary operators !
– Multiplicative operators * / %
– Additive operators + -
– Relational ordering < <= >= >
– Relational equality == !=
– Logical and &&
– Logical or ||
– Assignment =
Logical expression
Logical expression
• Expression that can be thought of as being true or false.– True if correct or false if not correct.
• The expression uses relational operators such as == and < and logical operators such as &&, ||, and !
Logical expression
• Logical expressions can be unpredictable• The following expression appears to represent a
comparison of 0, num = 12, and 10: 0 <= num <= 10
• It always evaluates true because 0<=12 evaluates to 1, and 1 <= 10 is true.
• A correct way to write this expression is:
0 <= num && num <= 10
Logical expression
• Example:
a) (true || false)
b) (7>3 && 5<2)
c) (5*4<20 || false)
Exercises • Assume x =5, y = 6 and z =7
Boolean expression Value
x<y && z>y
x<=z && x>0
x>=y && z==3
y<15||!(y>0)
x>y||z>y && !(z<=0)
Exercises Evaluate the following expression:
(17 < 4 * 3 + 5) || (8 * 2 == 4 * 4) &&
!(3 + 3 == 6)
C++ Programming: From Problem
Analysis to Program Design, Fourth
Edition
23
Comparing Characters
C++ Programming: From Problem
Analysis to Program Design, Fourth
Edition
25
Relational Operators and thestring Type
• 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
C++ Programming: From Problem
Analysis to Program Design, Fourth
Edition
26
Relational Operators and thestring Type (continued)
• Suppose we have the following declarations:string str1 = "Hello";
string str2 = "Hi";
string str3 = "Air";
string str4 = "Bill";
string str4 = "Big";
C++ Programming: From Problem
Analysis to Program Design, Fourth
Edition
27
Relational Operators and thestring Type (continued)
C++ Programming: From Problem
Analysis to Program Design, Fourth
Edition
28
Relational Operators and thestring Type (continued)
C++ Programming: From Problem
Analysis to Program Design, Fourth
Edition
29
Relational Operators and thestring Type (continued)
C++ Programming: From Problem
Analysis to Program Design, Fourth
Edition
30
Logical (Boolean) Operators and Logical Expressions
• Logical (Boolean) operators enable you to combine logical expressions
unary
binary
binary
C++ Programming: From Problem
Analysis to Program Design, Fourth
Edition
31
Logical (Boolean) Operators and Logical Expressions (continued)
Decision control structure
Decision control instruction
Example 1 Example 2
If (it is raining)wear a rain coatbring an umbrella
If (you have a test tomorrow)study tonight
Elsewatch a movie
You use the decision control structure or selection control sturcture when
you want program to make a decision or comparison and then select one of two paths,
depending on the result of that decision or comparison.
Decision control structure
1
One way selection
2
Two way selection
3
Multiple selection
One way selection
• The syntax of one-way selection is:
if (expression)
statement;
• Statement is executed if the value of the expression is true (1)
• Statement is by passed if the value is false(0); program goes to the next statement
Boolean expression in if condition
• if (quantity <50)
• if (age>=25)
• if (onhand == target)
• if (quantity != 7500)
One way selection
• Pseudocode:
• Flowchart:
if (expression) then
statements
end if
Expression
True
False
Statements
Example
Problem statement:
If the speed of the car is greater than 80km/h, then output a message “you are too fast!”
Begin
input speed
if speed > 80
output “you are too fast!”
end if
End speed>80
Input speed
TYou are too
fast
F
Start
End
Example #include <iostream>
using namespace std;
int main()
{
int speed;
cout<< “Enter your speed “;
cin >> speed;
if (speed > 80)
cout << “you are too fast!”;
}
Exercises 1#include <iostream>
using namespace std;
int main()
{
int mark;
cin >> mark;
if (mark >= 50)
cout << “PASSED!”;
return 0;
}
Exercises 2#include <iostream>
using namespace std;
int main()
{
int mark;
cin >> mark;
if (mark >= 50)
cout << “PASSED!”;
cout<< “thank you for using the program”<<endl;
return 0;
}
Compound statements
– Use the symbols { and } to group several statements as a single unit.
– Simple statements within the compound statements end with semicolons.
– Compound Statements are sometimes called a statement block.
– Use compound statements in an if statement if you want several actions executed when the Boolean expression is true.
Compound statements (cont.)
int main()
{
int mark;
cin >> mark;
if (mark >= 50)
cout << “PASSED!”;
cout<< “thank you”<<endl;
return 0;
}
int main()
{
int mark;
cin >> mark;
if (mark >= 50)
{
cout << “PASSED!”;
cout<< “thank you”<<endl;
return 0;
}
}
Single statement
compound statements
Two way 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
• if and else is a reserved word
Two way selection
• Pseudocode:
if (expression) then
statement1
else
statement2
end if
Two way selection
• Flowchart:
Expression
True
False
Statement1
Statement2
Example
Program segment Flowchart
if (cgpa < 2.0)
status = ‘F’;
else
status = ‘P’;
if (choice == 1)
gender = ‘F’;
else
gender = ‘M’;
cgpa < 2.0
P F
choice == 1
M F
true
true
false
false
Example
Problem statement:
If student marks greater than or equal to 50, then output a message “pass”, else “fail”.
Pseudocode:
Begin
input marks
if marks >= 50 then
output “pass”
else
output “fail”
end if
End
Example
• Flowchart
marks>=40
Input marks
TPass
F
Start
End
Fail
Example #include <iostream>
Using namespace std;
int main()
{
int marks;
cin >>marks;
if (marks >= 50)
cout << “pass”;
else
cout << “fail”;
return 0;
}
Compound statements
Compound statements (cont.)
if (marks >= 50)
{
cout << “pass”<<endl;
cout << “Good job!!”;
}
else
{
cout << “fail”;
cout << “Try again!!”;
}
Compound statements (cont.)• Syntax and code:#include <iostream>
using namespace std;
int main()
{
int marks;
cin >> marks;
if (marks >= 50)
cout << “pass”;
else
{
cout << “fail”;
cout << “you have to have to repeat”;
}
return 0;
}
Exercise
1. Assume that a program need to determine whether a student’s gender is male or female. If student’s gender equal to ‘f’ then display female; otherwise display male. Write pseudocode for the selection structure.
2. Write a C++ if statement that corresponds to the pseudocode in question 1.
Exercise (cont.)
3. Problem statement:
A shopkeeper sells a magazine for RM2.00 each. However, if the customer buys more than 10 magazines, the price of the magazine is only RM1.50 each. Calculate the total the customer has to pay based on the quantity that he buys.
Begin
input quantity
if quantity > 10 then
price = 1.50
else
price = 2.00
total = price * quantity
output total
End
Input quantity
T
Display total
F
quantity>10
price = 2.00 price = 1.50
Total = quantity * price
Start
End
• Syntax and code#include <iostream>
using namespace std;
int main()
{
int quantity = 0;
float total = 0;
cin >> quantity;
if (quantity > 10)
price = 1.50;
else
price = 2.00
total = quantity * price;
cout << total;
return 0;
}
Exercise (one way VS two way)
• A group of one way selection structure:
• Two way selection structure:
int x = -3;
if(x<10)
x = * x;
else
x = x + 10;
cout<<x;
int x = -3;
if(x<10)
x = * x;
if(x<100)
x = x + 10;
cout<<x;
Determine the output of both program segment: