Presentation is loading. Please wait.

Presentation is loading. Please wait.

Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.

Similar presentations


Presentation on theme: "Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution."— Presentation transcript:

1 Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution Three types Sequential Selection Repetition

2 Sequential Execution A compound statement is used to specify sequential control Compound statement A “grouping” of statements Each statement is executed in sequence Enclosed in braces “{ }” main() is a compound statement!!! { statement1; statement2; … statementn; } Compound Statement

3 Scope (and globals) #include <iostream> using namespace std; // global variable int iglobal= 10; // main function int main() { int imain= 20; cout << "In main:" << endl; cout << " iglobal= " << iglobal << endl; cout << " imain = " << imain << endl; cout << endl; // compound statement block { int icomp= 30; cout << "In control:" << endl; cout << " icomp = " << icomp << endl; } // uncomment the following - it will not compile!!!! // cout << "icomp = " << icomp << endl; Variables (incl. functions) defined with a compound statement “block” are “local” to that block They are not available outside the block, however… Variables defined in an enclosing block can be seen in the enclosed block Example: function parameters!!! And any variables defined in a function

4 Selection statements Control structures that conditionally execute statements Enables decision making if statement Uses a Boolean expression to decide whether the statements inside a compound statement should be executed switch statement Executes statements based on whether a value matches one of a list of specified alternatives

5 “if/else” statement A selection statement that conditionally executes based on whether a Boolean expression evaluates to true or false if (condition) statement; Example: if (age >= 21) cout << “legal!!!” << endl; if (condition) statement1; else statement2; Example: if (age >= 21) cout << “legal!!!” << endl; else cout << “Sorry!!!” << endl; Logical (Boolean) expression With an “else” condition

6 Selection (“if/else”, with a compound statement)
Logical (Boolean) expression if (condition) { statement1; statement2; … } else { alternative; } Compound Statement Compound Statement

7 Relational and Equality Operators
Used to construct Logical, or Boolean, expressions Expressions are used to perform tests to determine whether/which statements should be executed Typical forms: variable relational-operator variable A > B variable relational-operator constant A > 5 variable equality-operator variable A == B variable equality-operator constant A == 5 Evaluate to Boolean (bool) value of true or false

8 Selection (with a compound statement)
Logical (Boolean) expression “A>B” Relational operator “>” if (A > B) { statement1; statement2; … } Compound Statement

9 Rational and Equality Operators

10 Example x y x >= y -5 7 -5 7 false

11 Logical Operators && (and) || (or) ! (not)
Used to form more complex conditions, e.g. (salary < minSalary) || (dependents > 5) (temperature > 90.0) && (humidity > 0.90) winningRecord && (!probation)

12 && Operator (and)

13 || Operator (or)

14 ! Operator (not)

15 Examples int age; bool a, b; … … If (age > = 16) { If (a && b) {
cout << “you can drive!”; } bool a, b; If (a && b) { cout << “both true!”; } Note: it is possible to set a bool variable to the result of a logical expression! Ex: bool istrue= !a && age > 21;

16 Operator Precedence

17 Example x y z flag 3.0 4.0 2.0 false x + y / z <= 3.5 2.0 5.0 false

18 Example ! flag || (y + z >= x - z) x y z flag 3.0 4.0 2.0 false
true 6.0 1.0 true true

19 English Conditions as C++ Expressions

20 Comparing Characters and Strings
Letters are in typical alphabetical order Upper and lower case significant Digit characters are also ordered as expected String objects require string library Compares corresponding pairs of characters Based on numerical comparisons of ASCII integer values

21 Examples of Comparisons

22 Boolean Assignment Assignment statements have general form
variable = expression; E.g.: (for variable called same of type bool) same = true; same = (x == y);

23 Additional Examples inRange = (n > -10) && (n < 10); isLetter = ((‘A’ <= ch) && (ch <= ‘Z’)) || ((‘a’ <= ch) && (ch <= ‘z’)); even = (n % 2 == 0);

24 Writing bool Values Boolean values are represented by integer values in C++ 0 for false non-zero (typically 1) for true Outputting (or inputting) bool type values is done with integers

25 Short Circuit Evaluation
Evaluation of a logical expression concludes immediately when the result is determined (single == ‘y’ && gender == ‘m’ && age >= 18) If single is false, gender and age are not evaluated (single == ‘y’ || gender == ‘m’ || age >= 18) If single is true, gender and age are not evaluated

26 Intro to nesting and multiple alternative
void displayGrade (int score) { if (score >= 90) cout << "Grade is A " << endl; if (score >= 80) cout << "Grade is B " << endl; if (score >= 70) cout << "Grade is C " << endl; if (score >= 60) cout << "Grade is D " << endl; else cout << "Grade is F " << endl; } What is wrong with this? what happens if: score = 75? score = 50?

27 Does this fix it? Each if statement covers a non-overlapping range.
void displayGrade (int score) { if (score >= 90 && score <= 100) cout << "Grade is A " << endl; if (score >= 80 && score < 90) cout << "Grade is B " << endl; if (score >= 70 && score < 80) cout << "Grade is C " << endl; if (score >= 60 && score < 70) cout << "Grade is D " << endl; if (score < 60) // no more else! cout << "Grade is F " << endl; } Each if statement covers a non-overlapping range.

28 Another Solution is to use “nesting” Nested logic is one control structure containing another similar control structure

29 Writing a Nested if as a Multiple-Alternative Decision
Nested if statements can become quite complex. If there are more than three alternatives and indentation is not consistent, it may be difficult to determine the logical structure of the if statement. So, another approach is to use “multiple-alternative” coding

30 Multiple-Alternative Decision Form
if (condition1) statement1; else if (condition2) statement2; . else if (conditionn) statementn; else statemente;

31 Using Multiple Alternative
void displayGrade (int score) { if (score >= 90) cout << "Grade is A " << endl; else if (score >= 80) cout << "Grade is B " << endl; else if (score >= 70) cout << "Grade is C " << endl; else if (score >= 60) cout << "Grade is D " << endl; else cout << "Grade is F " << endl; }

32 Order of Conditions Matters
if (score >= 60) cout << "Grade is D " << endl; else if (score >= 70) cout << "Grade is C " << endl; else if (score >= 80) cout << "Grade is B " << endl; else if (score >= 90) cout << "Grade is A " << endl; else cout << "Grade is F " << endl;

33 The switch Control Statement
switch ( switch-expression ) { case label1: statements1; break; case label2: statements2; . case labeln: statementsn; default: statementsd; // optional }

34 Switch Control Statement
Alternative to multiple if statements in some cases Most useful when switch selector is single variable or simple expression Switch selector must be an integral type (int, char, bool)

35 Switch Control Statement
Switch selector value compared to each case label. When there is an exact match, statements for that case are executed. If no case label matches the selector, the entire switch body is skipped unless it contains a default case label. break is typically used between cases to avoid fall through.

36 switch statement to determine life expectancy of a lightbulb

37 Avoid Programming Errors
Use parentheses to clarify complex expressions Use logical operators only with logical expressions Use brackets { } to group multiple statements for use in control structures

38 Avoid Programming Errors
When writing a nested if statement, use multiple-alternative form if possible if conditions are not mutually exclusive, put the most restrictive condition first Make sure switch selector and case labels are the same type. Provide a default case for a switch statement whenever possible.


Download ppt "Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution."

Similar presentations


Ads by Google