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

Chapter 3 Part 1n2

fizik and programming

Uploaded by

wan zara sofiya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Chapter 3 Part 1n2

fizik and programming

Uploaded by

wan zara sofiya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

27/8/2024

Control Structures
Part 1

Learning outcome

In this topic, you will be able to :


➢understand and apply relational and logical operators
➢create and evaluate logical (Boolean) expressions
➢use relational operators with string data type
➢explain the concept of short-circuit evaluation
➢use the if and if…else statement

1
27/8/2024

Control Structures (1 of 2)
➢A computer can proceed:
• In sequence
• Selectively (branch): making a choice
• Repetitively: looping
• By calling a function

➢The two most common control structures are:


• Selection
• Repetition

Control Structures (2 of 2)

2
27/8/2024

RELATIONAL A relational operator checks the relationship between two


operands. If the relation is true, it returns 1; if the relation is
OPERATORS false, it returns value 0.

Operator Meaning Example


> Greater than height> 6.2

>= Greater than or equal to temp >= 98.6

< Less than age < 30

<= Less than or equal to taxable <= 20000

== Equal to grade == ‘A’

!= Not equal to number != 250

Relational expression

➢It is an expression used to compare two operands.


➢It is also referred to as a condition.
➢It contains operands and relational operators.
➢The result of the relational expression can be either a zero (false)
or non-zero (true) value. relational operator

price < 12.5

operand operand

3
27/8/2024

Confusion Between the Equality (==) and


Assignment (=) Operators
➢C++ allows you to use any expression that can be
evaluated to be either true or false as an expression
WARNING!
in the if statement
The equality operator is two
= symbols together. Don’t
if (x = 5)
confuse this operator with
cout << "The value is five." << endl; the assignment operator,
which is one = symbol.

➢The appearance of = in place of == resembles a silent


killer
• It is not a syntax error
• It is a logical error

Relational expressions (1 of 3)

Suppose i = 1, j = 2 and k = 3:

Expression True / False Value


(i + j) >= (k + 5) False 0

3 >= 8
i != (2 * j – 1) True 1

1 != 3

4
27/8/2024

Relational expressions (2 of 3)

➢Note: Arithmetic operators have higher precedence than relational


operators
Statements Output
cout << (9 * 3 < 4 * 5); 0

27 < 20 => False


cout << (9 * (3 < 4) * 5); 45

9*1*5

Note: True = 1

Relational expressions (3 of 3)
Assume x is 10, y is 7, and z, a and b are int or bool

Statement Outcome
z=x<y z is assigned 0 because x is not less than y .
cout << (x > y); Displays 1 because x is greater than y.
a = x >= y; a is assigned 1 because x is greater than or equal to y.
cout << (x <= y); Displays 0 because x is not less than or equal to y .
b = y != x; b is assigned 1 because y is not equal to x .

10

5
27/8/2024

Comparing Characters (1 of 2)

In an expression of
character values using
relational operators:
✓ The result depends on
the lexicographic order
(numeric values
assigned to each
character)
✓ ASCII character set

11

Comparing Characters (2 of 2)
Expression Value Interpretation
‘A’ > ‘C’ 0 false
‘D’ <= ‘Z’ 1 true
‘E’ == ‘F’ 0 false
‘g’ >= ‘m’ 0 false
‘b’ != ‘c’ 1 true
‘a’ == ‘A’ 0 false

12

6
27/8/2024

Assuming x is 5, y is 6 and z is 8, indicate whether each of the following relational


expressions is true or false:
No Relational expressions Answer
a) x == 5
b) 7 <= (x + 2)
c) z < 4
d) (2 + x) != y
e) z != 4
f) x >= 9
g) x <= (y * 2)

13

What will the following program display?

14

7
27/8/2024

bool Data Type (1 of 2)

➢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

15

bool Data Type (2 of 2)


Program Output

As you can see from the program


output, the value true is represented
in memory by the number 1, and
false is represented by 0.

16

8
27/8/2024

Logical (Boolean) Operators (1 of 4)

➢Logical (Boolean) operators enable you to combine relational


expressions
Operator Description Effect
Makes a true expression false, and a false
! NOT
expression true.
Both expressions must be true for the overall
&& AND
expression to be true.
One or both expressions must be
true for the overall expression to be true. It is
|| OR
only necessary for one to
be true, and it does not matter which.
17

Logical (Boolean) Operators (2 of 4)

Expression !(Expression)
true (nonzero) false (0)
false (0) true (1)

18

9
27/8/2024

Logical (Boolean) Operators (3 of 4)


Expression1 Expression2 Expression1 && Expression2
true (nonzero) true (nonzero) true (1)
true (nonzero) false (0) false (0)
false (0) true (nonzero) false (0)
false (0) false (0) false (0)

19

Logical (Boolean) Operators (4 of 4)


Expression1 Expression2 Expression1 || Expression2
true (nonzero) true (nonzero) true (1)
true (nonzero) false (0) true (1)
false (0) true (nonzero) true (1)
false (0) false (0) false (0)

20

10
27/8/2024

Order of Precedence (1 of 3)
Operators Associativity
➢Relational and logical operators
!, ++, -- (unary operators) Right to left
are evaluated from left to right
( ) Right to left
• The associativity is left to right
*, /, % Left to right
➢Parentheses can override
+, - Left to right
precedence <, <=, >=, > Left to right
==, != Left to right
&& Left to right
|| Left to right
=, +=, -=, *=, /= Right to left

21

Order of Precedence (2 of 3)
Suppose you have
the following
declarations:

22

11
27/8/2024

Order of Precedence (3 of 3)
Suppose you have
the following
declarations:

23

Write relational expressions to express the following conditions (using variable names of your choosing):
1. A person’s age is equal to 30.
2. A person’s temperature is greater than 98.6 degrees.
3. A person’s height is less than 6 feet.
4. The letter input is m.
5. A person’s age is equal to 30, and the person is taller than 6 feet.
6. The current day is the 15th day of the 1st month.
7. A person is older than 50 or has been employed at the company for at least 5 years.
8. A person’s identification number is less than 500 and the person is older than 55.
9. A length is greater than 2 feet and less than 3 feet.

24

12
27/8/2024

Relational Operators and the string Type (1 of 5)

Relational operators can be applied to variables of type


string
➢Strings are compared character by character, starting with the first
character
➢The characters are compared based on ASCII code
➢Comparison continues until either a mismatch is found, or all
characters are found equal

25

Relational Operators and the string Type (2 of 5)


➢For example, consider this comparison: "apple" < "application"
• The first character of both strings is 'a', so the comparison continues.
• The second character of both strings is 'p', so the comparison continues.
• The third character of both strings is 'p', so the comparison continues.
• The fourth character of both strings is ‘l', so the comparison continues.
• The comparison stops at the fifth character because a mismatch has been
found.
➢The value “apple” is lesser than the value “application”. This is because
the “e” in “apple” has a lesser ASCII value than the “i” in “application”

26

13
27/8/2024

Relational Operators and the string Type (3 of 5)


Expression Value/Explanation
Suppose you have the str1 < str2 true
following declarations: str1 = "Hello" and str2 = "Hi". The first character
of str1 and str2 are the same, but the second character
string str1 = 'e' of str1 is less than the second character 'i' of str2.
“Hello”, Therefore, str1 < str2 is true.
str2 = “Hi”,
str3 = “Air”,
str1 > "Hen" false
str4 = “Bill”, str1 = "Hello". The first two characters of str1 and
str5 = “Big”; "Hen" are the same, but the third character 'l' of str1
is less than the third character 'n' of "Hen". Therefore,
str1 > "Hen" is false.
str3 < "An" true
str3 = "Air". The first characters of str3 and "An" are
the same, but the second character 'i' of "Air" is less
than the second character 'n' of "An". Therefore, str3 <
"An" is true.
27

Relational Operators and the string Type (4 of 5)


Expression Value/Explanation
Suppose you have the str1 == "hello" false
following str1 = "Hello". The first character 'H' of str1 is less
declarations: than the first character 'h' of "hello" because the ASCII
value of 'H' is 72, and the ASCII value of 'h' is 104.
string str1 =
Therefore, str1 == "hello" is false.
“Hello”,
str2 = “Hi”, str3 <= str4 true
str3 = “Air”, str3 = "Air" and str4 = "Bill". The first character
str4 = “Bill”, 'A' of str3 is less than the first character 'B' of str4.
str5 = “Big”; Therefore, str3 <= str4 is true.
str2 > str4 true
str2 = "Hi" and str4 = "Bill". The first character 'H'
of str2 is greater than the first character 'B' of str4.
Therefore, str2 > str4 is true.

28

14
27/8/2024

Relational Operators and the string Type (5 of 5)

Suppose you have the Expression Value/Explanation


following str4 >= "Billy" false
declarations: str4 = "Bill". It has four characters and "Billy" has
five characters. Therefore, str4 is the shorter string. All
string str1 = four characters of str4 are the same as the corresponding
“Hello”, first four characters of "Billy", and "Billy" is the larger
str2 = “Hi”, string. Therefore, str4 >= "Billy" is false.
str3 = “Air”,
str4 = “Bill”, str5 <= "Bigger" true
str5 = “Big”; str5 = "Big". It has three characters and "Bigger" has
six characters. Therefore, str5 is the shorter string. All
three characters of str5 are the same as the corresponding
first three characters of "Bigger", and "Bigger" is the
larger string. Therefore, str5 <= "Bigger" is true.

29

Indicate whether each of the following relational expressions is True or


False. Refer to the ASCII table in the previous slide if necessary.
1. “Bill” == “BILL”
2. “Bill” < “BILL”
3. “Bill” < “Bob”
4. “189” > “23”
5. “189” > “Bill”
6. “Mary” < “MaryEllen”
7. “MaryEllen” < “Mary Ellen”

30

15
27/8/2024

Short-Circuit Evaluation
➢Short-circuit evaluation is a programming concept in which the compiler skips the
execution or evaluation of some sub-expressions in a logical expression.
➢The compiler stops evaluating the further sub-expressions as soon as the value of
the expression is determined.
If the expression age >= 21 is true, then
➢Example: x == 5 is not evaluated because the
expression’s result has already been
determined
(age >= 21) || (x == 5)
Similarly, if the expression grade ==
‘A’ is false, then x >= 7 is not
(grade == ‘A’) && (x >= 7) evaluated.

31

Comparing Floating-Point Numbers for Equality: A


Precaution (1 of 3)
➢Comparison of floating-point numbers for equality may not behave as you would
expect
➢Consider the following expression in C++:
1.0 == 3.0/7.0 + 2.0/7.0 + 2.0/7.0
This expression is considered false, even though the mathematical result of 3.0/7.0 +
2.0/7.0 + 2.0/7.0 is 1.0.
➢Why? The computer evaluates each as follows:
• 3.0/7.0 evaluates to 0.42857142857142855
• 2.0/7.0 evaluates to 0.2857142857142857
• and their sum is 0.9999999999999999
which is not exactly equal to 1.0 due to the limited precision of floating-point representation.

32

16
27/8/2024

Comparing Floating-Point Numbers for Equality: A


Precaution (2 of 3)
Solution: Using a Tolerance Value
➢To compare floating-point numbers for
EPSILON can be a constant set to
equality, we can use a tolerance value, often any acceptably small value, such as
called an EPSILON (ε). 0.000001.
operand_1 == operand_2

should be replaced by this condition:


abs(operand_1 – operand_2) < EPSILON

33

Comparing Floating-Point Numbers for Equality: A


Precaution (3 of 3)
The program checks if the
absolute difference
between x and y is less
than EPSILON. If it is, it
prints that they are equal
within the tolerance;
otherwise, it states they
are not equal.

34

17
27/8/2024

Associativity of Relational Operators: A Precaution


(1 of 3)
#include <iostream>
using namespace std;
int main()
The correct way is:
{
int num; if (num >= 0 && num <= 10)
cout << "Enter an integer: ";
cin >> num;
cout << endl;
Incorrect!
if (0 <= num <= 10)
cout << num << " is within 0 and 10." << endl;
else
cout << num << " is not within 0 and 10." <<
endl;
return 0;
}

35

Associativity of Relational Operators: A Precaution


(2 of 3)
➢Let say the value for num is 5

0 <= num <= 10 = 0 <= 5 <= 10 Relational operators are evaluated from left to right.
= (0 <= 5) <= 10 0 <= 5 will be evaluated and the result is true. The
value true is represented in memory by the number 1
= 1 <= 10 Therefore, the expression 0 <= 5 evaluates to 1.
Next, it compares 1 <= 10
= 1 (true)

18
27/8/2024

Associativity of Relational Operators: A Precaution


(3 of 3)
➢Let say the value for num is 20
0 <= num <= 10 = 0 <= 20 <= 10
= (0 <= 20) <= 10 0 <= 20 will be evaluated and the result is true. The
value true is represented in memory by the number 1
= 1 <= 10 Therefore, the expression 0 <= 20 evaluates to 1.
Next, it compares 1 <= 10
= 1 (true)

SELECTION STRUCTURE
❑ There are three types of selection structures in C++ language:

➢ if
• used for one-way selection
• used when we want a single or a group of statements to be executed if the condition is true
➢ if-else
• used for two-way selection
• the else statement will be executed when the condition is false

➢ switch or if-else-if
• used for multi-way selection
• allow us to select one from multiple options

38

19
27/8/2024

One-Way Selection (1 of 4)
➢One-way selection syntax

(decision maker)
(action statement)

➢The statement is:


• Executed if the value of the expression is true
• Bypassed if the value is false; program goes to the next statement
➢The expression is also called a decision maker
➢The statement following the expression is also called the action statement

39

One-Way Selection (2 of 4)

A bank would like to send a notice to a customer if her account balance


falls under a certain minimum value. If the account balance is below the
required minimum, send notice. Otherwise, do nothing :

40

20
27/8/2024

One-Way Selection (3 of 4)

WARNING!

You must not put a semicolon after the if


(expression)portion of an if
statement.

if (expression) no semicolon here


statement;

41

One-Way Selection (4 of 4)

The program prints


the positive
number entered by
the user. If the
user enters a
negative number,
no output will be
printed

42

21
27/8/2024

Write an if statement that performs the following logic:


1. If the variable x is equal to 20, then assigns 0 to the variable y.

2. If the variable price is greater than 500m then assign 0.2 to the variable
discountRate.

3. If the variable hours is greater than 40 then multiply payrate by 1.5.

43

Two-Way Selection (1 of 4)
➢Two-way selection syntax

➢If expression is true, statement1 is executed; otherwise, statement2


is executed
• statement1 and statement2 are any C++ statements

44

22
27/8/2024

Two-Way Selection (2 of 4)

45

Two-Way Selection (3 of 4)

In this example,

if...else statement
is used to check whether
a number entered by the
user is even or odd.

46

23
27/8/2024

Write an if...else statement that performs the following logic:


1. If the variable y is equal to 100 then assign 1 to x. Otherwise, assign 0 to x.

2. If the variable sales is greater than or equal to 50000.00 then assign 0.20
commissionRate. Otherwise, assign 0.10 to commissionRate.

47

Compound (Block of) Statements (1 of 4)


➢If you want your if...else statement to conditionally execute a group
of statements, use a set of braces to enclose the statements.
➢A compound statement (block of statements) has this form:

➢A compound statement functions like a single statement

48

24
27/8/2024

Compound (Block of) Statements (2 of 4)


if (age > 18)
{
cout << "Eligible to vote." << endl;
cout << "No longer a minor." << endl;
}
else
{
cout << "Not eligible to vote." << endl;
cout << "Still a minor." << endl;
}

49

Compound (Block of) Statements (3 of 4)

50

25
27/8/2024

Compound (Block of) Statements


(4 of 4)

51

Block Scope (1 of 2)

➢Determines the visibility and lifetime of variables within a specific


block of code.
➢A block is typically defined by a set of curly braces {} that enclose a
group of statements.
➢All statements in a compound statement constitute a single block of
code, and any variable declared in this block has meaning only
between its declaration and the closing braces defining the block.

52

26
27/8/2024

Block Scope (2 of 2)

This section of code produces the following


output:

The value of a is 25 and b is 17


a is now 46.25 b is now 17 and c
is 10
a is now 25 and b is 17

53

1. In a pass/fail course, a student passes if the grade is greater than or


equal to 70 and fails if the grade is lower than 70. Write a C++
program that accepts a grade and prints the message “A passing
grade” or “A failing grade,” as appropriate.
2. If money is left in a particular bank for more than 5 years, the bank
pays interest at a rate of 4.5%; otherwise, the interest rate is 3.0%.
Write a C++ program that uses the cin object to accept the number
of years in the variable numYears and display the correct interest
rate, depending on the value input into numYears.

54

27
27/8/2024

Control Structures
Part 2

55

Learning Outcome

In this topic, you will be able to :


➢use the if…else…if and nested if statements
➢understand null statements
➢use conditional operator (?:) to make simple decisions
➢use the switch statement in a program
➢avoid bugs by avoiding partially understood concepts
➢use the assert function to terminate a program

56

28
27/8/2024

Nested if statements (1 of 3)

➢To test more than one condition, an if statement can be nested


inside another if statement.
➢For example, consider a banking program that determines whether a
bank customer qualifies for a special low interest rate on a loan. To
qualify, two conditions must exist: (1) the customer must be currently
employed, and (2) the customer must have recently graduated from
college (in the past 2 years).

57

Nested if statements (2 of 3)

58

29
27/8/2024

Nested if statements (3 of 3)
➢For readability and easier debugging, it’s important to use proper alignment and
indentation in a set of nested if statements.

59

Compare these two program segments


if (age <= 10) if (age <= 10)
cout << "child"; cout << "child";
if (age > 10 && age < 21) else if (age > 10 && age < 21)
cout << "teenager"; cout << "teenager";
if (age >= 21) else
cout << "adult"; cout << "adult";

Note: In this example, each of the if Note: In this example, if the first
statements is checked regardless condition is satisfied then the else part
whether the first if condition is true will not be checked.
or not

60

30
27/8/2024

if-else-if statement (1 of 2)
➢The if-else-if
statement tests a series of
conditions. It is often simpler
to test a series of conditions
with the if-else-if
statement than with a set of
nested if-else
statements.

61

if-else-if statement (2 of 2)
Assume that score is a variable of type int. Based on the value of the score, the
following code outputs the grade:
if (testScore >= 90)
cout << "Your grade is A.\n";
else if (testScore >= 80)
cout << "Your grade is B.\n";
else if (testScore >= 70)
cout << "Your grade is C.\n";
else if (testScore >= 60)
cout << "Your grade is D.\n";
else
cout << "Your grade is F.\n";

62

31
27/8/2024

What will the following code display?

63

The grade level of undergraduate college students is typically determined according to the
following schedule:

Number of Credits Completed Grade Level


Less than 32 Freshman
32 to 63 Sophomore
64 to 95 Junior
96 or more Senior

Using this information, write a C++ program that accepts the number of credits a student
has completed, determines the student’s grade level, and displays the grade level.

64

32
27/8/2024

Null statements (1 of 3)
➢represented by a single semicolon (;)
➢often used in situations where a statement is required by the syntax, but no
action needs to be taken.

if (condition) {
// Do something
}
else {
; // Null statement
}

65

Null statements (2 of 3)
int x = 10, y = 20;

if (x > y) {
cout << "x is greater than y" << std::endl;
}
else {
; // Null statement
}

66

33
27/8/2024

Null statements (3 of 3)
int choice = 2;

switch (choice) {
case 1: cout << "You selected option 1." << endl;
break;
case 2: ; // Null statement
break;
case 3: cout << "You selected option 3." << endl;
break;
default: cout << "Invalid choice." << endl;
break;
}

67

Conditional Operator (?:) (1 of 3)


➢Conditional operator (?:)
You can use the conditional
• Known as Ternary operator: takes three arguments operator to create short
➢Syntax for the conditional operator expressions that work like
if…else statements.

➢If expression1 is true, the result of the conditional expression is


expression2
• Otherwise, the result is expression3

68

34
27/8/2024

Conditional Operator (?:) (2 of 3)


➢Example: x < 0? y = 10 : z = 20;

➢The conditional expression above performs the same operation as the


following if...else statement:

if (x < 0)
y = 10;
else
z = 20;

69

Conditional Operator (?:) (3 of 3)


➢Here is an example of an assignment statement using the value of a
conditional expression:
a = x > 100 ? 0 : 1;
➢The value assigned to a will be either 0 or 1, depending upon whether x is
greater than 100. This statement could be expressed as the following
if...else statement:
if (x > 100)
a = 0;
else
a = 1;

70

35
27/8/2024

Rewrite the following if..else statements as conditional


expressions:

71

switch Statements (1 of 4)
➢switch statement is an alternate switch (Expression)
to if...else...if {
case Value1:
➢switch (integral) expression is // place one or more
evaluated first // statements here
case Value2:
➢Value of the expression // place one or more
determines which corresponding // statements here
action is taken // case statements may be
repeated as many // times as
➢Expression is sometimes called necessary
the selector default:
// place one or more
// statements here
}

72

36
27/8/2024

switch Statements (2 of 4)

73

switch Statements (3 of 4)
➢ Expression can be either
• a variable of any of the integer data types (including char)
• an expression whose value is of any of the integer data types
➢One or more statements may follow a case label
➢Braces are not needed to turn multiple statements into a single compound statement
➢When a case value is matched, all statements after it will be executed until a break is
encountered
➢ The expression following the word case must be an integer literal or constant. It cannot
be a variable, and it cannot be an expression such as x < 22 or n == 50
➢The break statement may or may not appear after each statement
➢switch, case, break, and default are reserved words

74

37
27/8/2024

switch Statements (4 of 4)
char choice;

cout << "Enter A, B, or C: ";


cin >> choice;
switch (choice)
{
case 'A': cout << "You entered A.\n"; break;
case 'B': cout << "You entered B.\n"; break;
case 'C': cout << "You entered C.\n"; break;
default: cout << "You did not enter A, B, or C!\n";
}

75

1. What is wrong with the following switch statement?

2. What will the following program segment display?

76

38
27/8/2024

assert function (1 of 4)

➢In C++, an assertion is a statement used to state or assert that the


expression must be true.

➢It is used to check the conditions that cannot happen unless there is a
bug. So, it is used as a debugging tool since it terminates the program
when the assertion becomes false.

77

assert function (2 of 4)
➢ This function is located in cassert header file
➢ Syntax

• expression is any logical expression


➢ If the expression evaluates to true, the next statement executes
➢ If the expression evaluates to false, the program terminates and indicates where in the
program the error occurred

➢ Certain types of errors are very difficult to catch


• Example: division by zero
➢ The assert function is useful in stopping program execution when certain elusive errors occur

78

39
27/8/2024

assert function (3 of 4)
In this example, we have used the
assert function to assert that the
value of even_num should be
even.

Since the value of even_num is 3,


the assertion even num % 2 ==
0 fails. As a result, the program
terminates and an error message is
printed.

But if we change even_num to 2,


the program executes without any
error.

79

assert function (4 of 4)

➢assert is useful for enforcing programming constraints during


program development
➢After developing and testing a program, remove or disable assert
statements
➢The preprocessor directive #define NDEBUG must be placed
before the directive #include <cassert> to disable the
assert statement

80

40

You might also like