Download presentation
Presentation is loading. Please wait.
Published byAngelina Cross Modified over 9 years ago
1
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical http://www.cs.odu.edu/~cs150/week_03/t hursSept_10/exampleLabFinal/ http://www.cs.odu.edu/~cs150/week_03/t hursSept_10/exampleLabFinal/ Template for project 1 is up Project 1 Due Date: Friday, September 25th 1
2
2
3
Quiz 6 Attendance (Print your name on the paper given to you) 3
4
Control Structures I (Selection) 4
5
Control Structures A computer can proceed: ◦ In sequence ◦ Selectively (branch): making a choice ◦ Repetitively (iteratively): looping ◦ By calling a function Two most common control structures: ◦ Selection ◦ Repetition 5
6
Control Structures (cont’d.) 6
7
Selection: if and if...else Selection or repetition requires execution of a logical expression: Logical expression: An expression that evaluates to true or false. ◦ “8 is greater than 3” (is this logical expression?) 7
8
8 > 3 (> is a relational operator in c++) 8
9
Relational Operators and Simple Data Types Relational operators: ◦ Allow comparisons ◦ Require two operands (binary) ◦ Evaluate to true or false Conditional statements: only executed if certain conditions are met Condition: represented by a logical (Boolean) expression that evaluates to a logical (Boolean) value 9
10
Relational Operators and Simple Data Types (cont’d.) Relational operators can be used with all three simple data types: 8 < 15 evaluates to true 6 != 6 evaluates to false 2.5 > 5.8 evaluates to false 5.9 <= 7.5 evaluates to true 10
11
Comparing Characters Expression of char values with relational operators ◦ Result depends on machine’s collating sequence ‘ ‘ < ‘a’ ASCII value of ‘ ‘ is 32 (Appendix C) ASCII value of ‘a‘ is 97 11
12
One-Way Selection One-way selection syntax: If the value of the expression is true: Statement is executed If the value of the expression is false: Statement does not execute & program goes to the next statement Expression sometimes is called a decision maker 12
13
One-Way Selection (cont’d.) 13
14
Example if (score >= 60) grade =‘P’; If the expression (score >= 60) evaluates to true the assignment statement grade =‘P’; executes If the expression (score >= 60) evaluates to false ? 14
15
In c++ any nonzero value is treated as true If (39){ Cout << “Hello”; } 15
16
Lets look at some Examples Ch4_CreditCardPenalty Nonzero true false example 16
17
Incorrect version of if statements if score >= 60 grade=‘P’;syntax error if (score >= 60); grade=‘P’;semantic error statement in line 2 executes regardless of how the if statement evaluates 17
18
Two-Way Selection Two-way selection syntax: If expression is true, statement1 is executed; otherwise, statement2 is executed ◦ statement1 and statement2 are any C++ statements 18
19
Two-Way Selection (cont’d.) 19
20
What’s wrong with this code? if ( score >=60 ) cout<< “Passing” << endl; elsecout<< “Failing” << endl; What happens if score=50 ? What happens if score=70 ? 20
21
The int Data Type and Logical (Boolean) Expressions Earlier versions of C++ did not provide built- in data types that had Boolean values Logical expressions evaluate to either 1 or 0 int legalAge; int age = 22; legalAge = (age >= 21) (assigns 1 to legalAge if age is >= 21) (otherwise assigns 0) 21
22
bool Data Type and Logical (Boolean) Expressions The data type bool has logical (Boolean) values true and false bool, true, and false are reserved words bool legalAge; int age = 22; legalAge = (age >= 21) (assigns true to legalAge if age is >= 21) (otherwise assigns false) 22
23
How to combine logical expressions? weight > 180 and height < 6.0 23
24
Logical (Boolean) Operators and Logical Expressions Logical (Boolean) operators: enable you to combine logical expressions 24
25
The ! NOT Operator 25
26
The && AND Operator 26
27
The || OR Operator 27
28
Order of Precedence 28
29
29
30
30
31
Example Ch4_LogicalOperatorsExample4-14 31
32
Relational Operators and the string 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 ◦ Comparison is based on ASCII 32
33
Relational Operators and the string Type ◦ 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 33
34
Suppose we have the following declarations: string str1 = "Hello"; string str2 = "Hi"; string str3 = "Air"; string str4 = "Bill"; string str4 = "Big"; 34
35
35
36
36
37
Compound (Block of) Statements A compound statement functions like a single statement but contains one or more statements enclosed in curly braces 37
38
Compound (Block of) Statements (cont’d.) 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; } 38
39
Multiple Selections: Nested if Nesting: one control statement is located within another An else is associated with the most recent if that has not been paired with an else 39
40
ß 40
41
41
42
42
43
Short-Circuit Evaluation Short-circuit evaluation: evaluation of a logical expression stops as soon as the value of the expression is known Example: (age >= 21) || ( x == 5)//Line 1 (grade == 'A') && (x >= 7) //Line 2 43
44
Input Failure and the if Statement Common causes of input failure: 1. Attempting to open an input file that does not exist 2. Attempting to read beyond the end of an input file Can use if statements to check status of input stream If stream enters the fail state, include instructions that stop program execution 44
45
if (!inFile){ cout<<“cannot open the input file”; return 1; } 45
46
Confusion Between the Equality (==) and Assignment (=) Operators C++ allows you to use any expression that can be evaluated to either true or false as an expression in the if statement: if (x = 5) cout << "The value is five." << endl; The appearance of = in place of == resembles a silent killer ◦ It is not a syntax error ◦ It is a logical error 46
47
In general the expression x=a where a is nonzero will always evaluate to true x=0 evaluates to ? 47
48
Conditional Operator (?:) Ternary operator: takes 3 arguments Syntax for the conditional operator: expression1 ? expression2 : expression3 If expression1 is true, the result of the conditional expression is expression2 ◦ Otherwise, the result is expression3 48
49
Example: max = (a >= b) ? a : b; if (a >= b) max = a; else max = b; 49
50
Program Style and Form: Indentation A properly indented program: ◦ Helps you spot and fix errors quickly Insert a blank line between statements that are naturally separate Two commonly used styles for placing braces ◦ On a line by themselves ◦ Or left brace is placed after the expression, and the right brace is on a line by itself 50
51
switch Structures switch structure: Another selection or branch structure Aternate to if-else switch (integral) expression is evaluated first This expression sometimes called selector Value of the expression determines which corresponding action is taken 51
52
52
53
53
54
Example Ch4_BreakInSwitch Ch4_GradeProgramWithBugs.cpp Ch4_CableCompany.cpp 54
55
Control Structures II (Repetition) 55
56
Why Is Repetition Needed? Repetition allows efficient use of variables Can input, add, and average multiple numbers using a limited number of variables For example, to add five numbers: ◦ Declare a variable for each number, input the numbers and add the variables together ◦ Create a loop that reads a number into a variable and adds it to a variable that contains the sum of the numbers 56
57
while Looping (Repetition) Structure Syntax of the while statement: expression acts as a decision maker and is usually a logical expression statement is called the body of the loop The parentheses are part of the syntax 57
58
while Looping (Repetition) Structure (cont’d.) 58
59
while Looping (Repetition) Structure (cont’d.) 59
60
The body of the while executes when the expression evaluates to true The expression checks whether a variable called loop control variable (LCV) satisfies certain condition Previous example i was LCV LCV should be initialized and eventually make the expression evaluate to false (We do this by updating LCV) 60
61
Generally while loops are written in the following form: /*initialize loop control variable*/ while (expression){ /*expression tests LCV*/ //update LCV } 61
62
while Looping (Repetition) Structure (cont’d.) 62
63
Case 1: Counter-Controlled while Loops When you know exactly how many times the statements need to be executed ◦ Use a counter-controlled while loop 63
64
Example Ch5_CounterControl.cpp 64
65
Case 2: Sentinel-Controlled while Loops Sentinel variable is tested in the condition Loop ends when sentinel is encountered 65
66
Example Ch5_SentinelControl.cpp 66
67
Case 3: Flag-Controlled while Loops Flag-controlled while loop: uses a bool variable to control the loop 67
68
Example Ch5_FlagControlledLoop.cpp 68
69
Case 4: EOF-Controlled while Loops End-of-file (EOF)-controlled while loop: when it is difficult to select a sentinel value 69
70
eof Function The function eof can determine the end of file status eof is a member of data type istream Syntax for the function eof : Ch5_EOFControlledLoop.cpp 70
71
for Looping (Repetition) Structure for loop: called a counted or indexed for loop Syntax of the for statement: The initial statement, loop condition, and update statement are called for loop control statements 71
72
for Looping (Repetition) Structure (cont’d.) 72
73
for Looping (Repetition) Structure (cont’d.) 73
74
for Looping (Repetition) Structure (cont’d.) 74
75
for Looping (Repetition) Structure (cont’d.) The following is a semantic error: 75
76
The following is a legal (but infinite) for loop: for (;;) cout << "Hello" << endl; 76
77
for Looping (Repetition) Structure (cont’d.) 77
78
do…while Looping (Repetition) Structure Syntax of a do...while loop: The statement executes first, and then the expression is evaluated ◦ As long as expression is true, loop continues To avoid an infinite loop, body must contain a statement that makes the expression false 78
79
do…while Looping (Repetition) Structure (cont’d.) The statement can be simple or compound Loop always iterates at least once 79
80
do…while Looping (Repetition) Structure (cont’d.) 80
81
do…while Looping (Repetition) Structure (cont’d.) 81
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.