Control Structures The if, for, and while Statements §5.1, §5.4, & §5.5 (Several examples here; also Lab #4) 1 Basic Kinds of Control The behavior of main()(and other functions) is determined by the statements within it. Statements fall into one of three categories called control structures: Statements that simply execute in ___________. Statements that _________ one of several alternatives. See flowcharts in §5.4 & 5.5 Statements that _________ another statement. EVERY PROGRAM CAN BE WRITTEN USING THESE 3 CONTROL STRUCTURES. 2 Sequential execution The design of computers in which program instructions are stored in memory along with the data processed by the program is known as the ____________________ Named after mathematician/ architecture. A special register, called the physicist John von Neumann _______________________ (IC), stores the address (see Ch.1, p. 8) of the memory location where the next instruction to be executed is found. It is initialized with the address of the first instruction and execution proceeds as follows: Fetch the instruction whose address is in the IC Decode it to find the opcode and the operands Execute the operation ______ (unless the IC is changed in some other way) 3 The last step (IC++) indicates that the default manner of executing statements is ______________________. In C++, a list of statements enclosed in curly braces { } Statement1 Statement2 ... StatementN STYLE TIP Indent& align the statements they enclose. is known as a (________________________________ or _________). It is a statement that produces sequential execution of the statements enclosed by the { and }. Note: A compound statement is a single statement and can thus be used any place a statement is needed . 4 Scope A variable declared in a block is called a ________ ___________. It exists (has memory allocated to it) only from its declaration to the end of the block. We say that its ____________ extends from its declaration to the end of the block. For example, in the code ... cin >> item; while (item != -999) { int i = 0; ... cin >> item; i++; } cout << "Value of i = " << i; This is one of several scope rules. Others will be described later. the last line won't compile because local variable i is out of scope. The "lifetime" of i ends at the }. 5 Selective Execution (§ 5.4) In contrast to sequential execution, there are situations in which a problem’s solution requires that a statement be executed selectively, based on a ___________ (a __________ expression): The C++ ________________ is a statement that causes selective execution, allowing a program to choose exactly one of two statements and execute it. Note again: An if statement is a single statement, even if it extends over many lines. if (Condition) Statement1 else Statement2 optional 6 The Simple if The C++ if statement has several different forms. The first form has no else or Statement2, and is called the simple if: if (Condition) Statement If Condition is true, Statement Statement is ____________ ; otherwise Statement is _________ . T Condition F 7 Examples: // if value is negative, make it positive if (value < 0) value = -value; // Display date in mm/dd/yyyy format if (month < 10) cout << 0; cout << month << '/'; if (day < 10) cout << 0; cout << day << '/' << year << endl; 8 Examples showing Statement can be a compound statement: // if a < b, interchange a and b (integers) if (a < b) Common Alternative Style: { if (a < b){ int temp = a; int temp = a; a = b; a = b; b = temp; b = temp; } } // Stop program if a is 0 // (in quadratic equation solver) cout is buffered; cerr is not. if (a == 0) { cerr << "*** Coefficient of x^2 cannot be 0 ***\n"; ____________; // Stop execution & return 1 to OS } Lab 4: Exer. 4.3 9 The Two-Branch if In the second form of if, the else and Statement2 are present: if (Condition) Statement1 else Statement2 STYLE TIP Align if and else and indent & align the statements in each part.. If Condition is true, T Statement1 is __________ and Statement2 is _________; Statement1 otherwise Statement1 is ___________ and Statement2 is ________________. The ternary operator ? : is essentially an inline if of this form. Condition F Statement2 10 Example: // Continuation of quadratic equation solver // Legal quadratic equation, so find roots (if any) double discrim = b*b - 4*a*c; if (discrim >= 0) { double root1 = (-b + sqrt(discrim)) / (2*a), root2 = (-b - sqrt(discrim)) / (2*a); cout << "Solutions: " << root1 << ", " << root2 << endl; } else cout << "No real roots\n"; 11 The Multi-branch if The final form of the if statement is: if (Cond1) Stmt1 else if (Cond2) Stmt2 ... else if (CondN) StmtN else StmtN+1 STYLE TIP Align if, else ifs, and else and indent & align the statements in each part. ________________ of the statements Stmti will be selected and executed, namely, the one corresponding to the first Condi that is true. 12 The intent is to implement a multi-alternative selection structure of the following form, where exactly one of the alternatives is selected and executed: Stmt1 Stmt2 Stmt3 StmtN StmtN+1 13 Actually, however, it implements a "waterfall" selection structure of the following form: T Stmt1 Cond1 T F Cond2 F ... Stmt2 T StmtN CondN F StmtN+1 14 And it is treated by the compiler as a sequence of ______________ in which each else clause (except the last) is another if-else statement: if (Cond1) Stmt1 else if (Cond2) Stmt2 else if (Cond3) Stmt3 ... else if (CondN) StmtN else StmtN+1 This form is surely more difficult to type with all its staggered indents. It also does not display as clearly the different alternatives and that exactly one of them will be selected. 15 If Cond1 is true, Stmt1 is executed and the remaining statements are skipped; otherwise, control moves to Cond2; if Cond2 is true, Stmt2 is executed and the remaining statements are skipped; otherwise, control goes to the next condition ... if CondN is true, StmtN is executed and StmtN+1 is skipped; otherwise, StmtN+1 is executed. if (Cond1) Stmt1 else if (Cond2) Stmt2 ... else if (CondN) StmtN else StmtN+1 16 Example: Assigning letter grades: Using the nested-if form: if (score > 100 || score < 0) cerr << "Invalid score!\n"; else if (score >= 90) grade = 'A'; else if (score >= 80) grade = 'B'; else if (score >= 70) grade = 'C'; else if (score >= 60) grade = 'D'; else grade = 'F'; 17 ... or the preferred if-else-if form: if (score > 100 || score < 0) cerr << "Invalid score!\n"; else if (score >= 90) Note the simple conditions;we don't grade = 'A'; need (score <= 100 && score >= 90) else if (score >= 80) (score < 90 && score >= 80) grade = 'B'; (score < 80 && score >= 70) else if (score >= 70) (score < 70 && score >= 60) grade = 'C'; Do you understand why? else if (score >= 60) grade = 'D'; else Here's an example of program grade = 'F'; efficiency — not doing unnecessary computations. 18 Repetitive Execution (§ 5.5) Finally, there are situations where solving a problem requires that a statement be repeated, with the repetition being controlled by a ___________. •There are three parts to the repetition mechanism: – Initialization – Repeated execution – Termination •Now we look at one repetition statement in C++, the for statement: 19 Does the initialization Causes termination — think "while this is true, do the following" Usually modifies something each time through the loop for (InitializerExpr; LoopCondition; ModifierExpr) Statement where Statement can be either a single statement, or a compound statement. And again, note: A for statement is a single statement, even if it extends over many lines. Need not all be on one line Compared to for statements in other programming languages, C++'s has an unusual syntax. 20 The for Loop for (InitializerExpr; LoopCondition; ModifierExpr) Statement Statement will be executed so long as ____________ ____________. Statement is often called the _ InitializerExpr F LoopCondition T Statement of the loop. ModifierExpr STYLE TIP Indent and align the statements in the body of the loop. 21 for (InitializerExpr; LoopCondition; ModifierExpr) _____ _____ Statement InitializerExpr Each execution of LoopCondition Statement ModifierExpr is called one repetition or iteration of the loop. F LoopCondition T Statement Modifierxpr 22 for (InitializerExpr; LoopCondition; ModifierExpr) Statement When LoopCondition becomes false,control proceeds to the statement ____________ ______________. Note: if the LoopCondition is initially false, then the body of the loop will _____________executed. For this reason this is called a ___________ loop. InitializerExpr F LoopCondition T Statement ModifierExpr 23 Counting The "normal" use of the for loop is to count: Declare and initialize the loopcontrol variable Check if loop-control variable has gone through all its values Inc-/dec-rement loop-control variable int limit; cin >> limit; for (______________________________________) { Could omit cout << count << endl; { }; loop body contains a single } statement Output (suppose limit = 5): What if limit is 1? limit is 0? How get 1, 3, 5, . . . ? _____ __________ Scope Rule 24 Nested Loops Loops can also be nested: Could omit { } since each loop body contains a single statement for (int val1 = 1; val1 <= limit1; val1++) { for (int val2 = 1; val2 <= limit2; val2++) { cout << val1 << '*' << val2 << " = " << val1 * val2 << endl; } } Output (suppose limit1 = 2, limit2 = 3): 1*1 1*2 1*3 2*1 2*2 2*3 = = = = = = 1 2 3 2 4 6 25 Input Loops There two different types of input loops: 1. ____________approach: Ask for the number of inputs to be entered and use a for loop. – This method requires knowing in advance how many inputs there are. Example: The Nyhoffian method of assigning letter grades: Find the mean of the numeric scores. This is the B- cutoff. Halfway between the mean and 100% is the A- cutoff. Halfway between the mean and 50% is the C- cutoff. 50% is the D- cutoff. 26 Example /* Program to display a grading scale (Nyhoffian) for a test. Input: A list of test scores Output: Letter grade cutoffs -----------------------------------------------------------*/ #include <iostream> using namespace std; int main() { cout << "Program finds letter grade cutoffs for a test.\n\n"; // First find the average double score, sum = 0.0, average; int numScores = 0; 27 cout << "Enter number of scores: "; cin >> numScores; for (int count = 1; count <= numScores; count++) { cout << "Enter a score: "; cin >> score; sum += score; } if (numScores > 0) average = sum / numScores; else { cerr << "\n*** No scores! Stopping program ***\n"; exit(1); } // Compute and display letter grade cutoffs. cout << << << << } "\nA-: "B-: " "C-: " "D-: " " << (100 + average) /2 << "%\n" << average << "%\n" << (average + 50) / 2 << "%\n" << 50 << "%\n"; 28 Execution of our example program: Program finds letter grade cutoffs for a test. Enter Enter Enter Enter Enter Enter A-: B-: C-: D-: number of scores: 5 a score: 77 a score: 88 a score: 66 a score: 77 a score: 99 90.7% 81.4% 65.7% 50% 29 The second kind of input loop: 2. ___________ approach: Values are entered until the end of input is signaled by entering a sentinel (or flag) ― a value that signals the end of input. - A _________ loop is commonly used in many programming languages. -This method requires the availability of an appropriate sentinel value. The while Loop Pattern: while (Expression) Statement Statement can be either a single or a compound statement, but is almost always compound. Repetition continues so long as Condition is true. F Condition T Statement 31 Using while for an Input Loop Pattern: Prompt for first value Read value while (value != sentinel) { Process the value } Need the first input value so it can be compared with sentinel Prompt for another value Read value Get the next value 32 Example /* Program to display a grading scale (Nyhoffian) for a test. Input: A list of test scores Output: Letter grade cutoffs -----------------------------------------------------------*/ #include <iostream> using namespace std; int main() { cout << "Program finds letter grade cutoffs for a test.\n\n"; // First find the average double score, sum = 0.0, average; int numScores = 0; •33 cout << "Enter a test score (-1 to quit): "; cin >> score; while (score >= 0) { numScores++; sum += score; cout << "Enter another score (-1 to quit): "; cin >> score; } if (numScores > 0) average = sum / numScores; else { cerr << "\n*** No scores! Stopping program ***\n"; exit(1); } sentinel // Compute and display letter grade cutoffs. cout << << << << } "\nA-: "B-: " "C-: " "D-: " " << (100 + average) /2 << "%\n" << average << "%\n" << (average + 50) / 2 << "%\n" << 50 << "%\n"; •34 Execution of our example program, but using the while-loop version: Program finds letter grade cutoffs for a test. Enter a test score (-1 to quit): 77 Enter another score (-1 to quit): 88 Enter another score (-1 to quit): 66 Enter another score (-1 to quit): 77 Enter another score (-1 to quit): 99 Enter another score (-1 to quit): -1 A-: 90.7% B-: 81.4% C-: 65.7% D-: 50% 35