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

Week5 Lecture2

The document discusses different conditional structures in programming including two-way selection, the conditional operator, nested if statements, if-else pairs, switch statements, and flags. It provides examples of how to use these structures and operators to make decisions in code based on different conditions.

Uploaded by

Komail Raza
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Week5 Lecture2

The document discusses different conditional structures in programming including two-way selection, the conditional operator, nested if statements, if-else pairs, switch statements, and flags. It provides examples of how to use these structures and operators to make decisions in code based on different conditions.

Uploaded by

Komail Raza
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Programming Fundamentals

Week5 Lecture 2
Making Decisions (Conditional Structures)

BS(Computer Science) Spring-2024

1
Agenda
 Making Decisions (Conditional Structures)
 Floating point undesirable equality errors (recap)
 Two-Way Selection
 Conditional Operator (?:) (Ternary operator)
 Multiple Selections: Nested if
 if-else Pairing
 switch Structures
 goto Statement
 Break and Continue
 assert Function
2
Flags
 Variable that signals a condition: usually implemented as a bool variable
 Can also be an integer
• The value 0 is considered false
• Any nonzero value is considered true
 As with other variables in functions, must be assigned an initial value before it is
used
bool salesQuotaMet = false; int salesQuotaMet = 0; // 0 means false.
if (sales >= QUOTA_AMOUNT) if (sales >= QUOTA_AMOUNT)
salesQuotaMet = true; salesQuotaMet = 1;
else else
salesQuotaMet = false; salesQuotaMet = 0;
if (salesQuotaMet) Testing of the flag in the following way:
cout << "You have met your sales quota!\n"; if (salesQuotaMet)
if (salesQuotaMet == true) //same as above cout << "You have met your sales quota!\n";
cout << "You have met your sales quota!\n"; 3
Logical Operators
 Logical operators connect two or more relational expressions into one or reverse
the logic of an expression
 Or: Used to create relational expressions from other relational expressions
 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
4
Logical Operators-Examples
int x = 12, y = 5, z = -4;
(x > y) && (y > z) true

(x > y) && (z > y) false

(x <= z) || (y == z) false

(x <= z) || (y != z) true

!(x >= z) false

5
The logical && operator in Program

6
The logical || Operator in Program

7
The logical ! Operator in Program

8
Logical Operator-Notes
 ! has highest precedence, 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)
 Used to test to see if a value falls inside a range:
if (grade >= 0 && grade <= 100)
cout << "Valid grade";
 Can also test to see if value falls outside of range:
if (grade <= 0 || grade >= 100)
cout << "Invalid grade";
 Cannot use mathematical notation:
if (0 <= grade <= 100) //doesn’t work!

9
Menus-driven programs
 Program execution controlled by user selecting from a list of actions
• Menu: list of choices on the screen
• Menus can be implemented using if/else if statements
 Menu-Driven Program Organization
• Display list of numbered or lettered choices for actions
• Prompt user to make selection
 Test user selection in expression
• if a match, then execute code for action
• if not, then go on to next expression

10
Validating User Input
 Input validation: inspecting input data to determine whether it is acceptable
 Bad output will be produced from bad input
 Can perform various tests:
• Range
• Reasonableness
• Valid menu choice
• Divide by zero

11
Example program (Input Validation in
Program)

12
Comparing Characters and Strings
 Characters are compared using their ASCII values
'A' < 'B'
• The ASCII value of 'A' (65) is less than the ASCII value of 'B'(66)
'1' < '2'
• The ASCII value of '1' (49) is less than the ASCI value of '2' (50)
• Lowercase letters have higher ASCII codes than uppercase letters, so 'a' > 'Z‘

13
Relational Operators Compare Characters

14
Comparing string Objects
 Like characters, strings are compared using their ASCII values
string name1 = "Mary";
string name2 = "Mark"; The characters in each
string must match before
name1 > name2 // true they are equal
name1 <= name2 // false
name1 != name2 // true
name1 < "Mary Jane"// true

15
The Conditional Operator (Ternary operator)
 Can use to create short hand if/else statements
 Format:
expr ? expr : expr;

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

First Expression: 2nd Expression: 3rd Expression:


Expression to be Executes if first Executes if the first
tested expression is true expression is false

• General Syntax: variable = (condition) ? expressionTrue : expressionFalse;

16
The Conditional Operator
 The value of a conditional expression is
• The value of the second expression if the first expression is true
• The value of the third expression if the first expression is false
 Parentheses () may be needed in an expression due to precedence of
conditional operator
 Example:
int time = 20;
string result = (time < 18) ? "Good day." : "Good evening.";
cout << result;

17
Example program (Ternary Operator)

18
The switch Statement
 Used to select among statements from several alternatives
 In some cases, can be used instead of if/else if statements
 Switch statement format
switch (expression) //integer
{
case exp1: statement1;
case exp2: statement2;
...
case expn: statementn;
default: statementn+1;
}
19
Flowcha
rt

20
Example Program (Switch Statement)

21
switch Statement Requirements
 expression must be an integer variable or an expression that evaluates to an
integer value
 exp1 through expn must be constant integer expressions or literals, and must
be unique in the switch statement
 default is optional but recommended
 How switch statement works?
• First: expression is evaluated
• Second: The value of expression is compared against exp1 through expn.
• Third: If expression matches value expi, the program branches to the
statement following expi and continues to the end of the switch
• If no matching value is found, the program branches to the statement after
default:
22
Break Statement
 Used to exit a switch statement
 If it is left out, the program "falls through" the remaining statements in the
switch statement

23
Program (break and default statements)

24
Using switch in Menu Systems
 switch statement is a natural choice for menu-driven program:
• display the menu
• then, get the user's menu selection
• use user input as expression in switch statement
• use menu choices as expr in case statements

25
More About Blocks and Scope
 Scope of a variable is the block in which it is defined, from the point of definition
to the end of the block
 Usually defined at beginning of function
 May be defined close to first use
 Inner Block Variable Definition

26
Variables with the Same Name

 Variables defined inside { } have local or block scope


 When inside a block within another block, can define variables with the same
name as in the outer block.
• When in inner block, outer definition is not available
• Not a good idea

27
Program (Two Variables with the Same Name)

28
Thank You All

? 

Acknowledgment: The slides are adapted from the 2012 Pearson Education, Inc.
29

You might also like