1 / 37

Control Structures

Learn about the basic kinds of control structures in programming, including sequential execution, conditional selection, and repetitive statements. Explore examples and see how every program can be written using these control structures.

reber
Download Presentation

Control Structures

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Control Structures The if, for, and while Statements §5.1, §5.4, & §5.5 (Several examples here; also Lab #4) 1 st. line

  2. 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 sequence. Statements that select one of several alternatives. Statements that repeat another statement. See flowcharts in §5.4 & 5.5 EVERY PROGRAM CAN BE WRITTEN USING THESE 3 CONTROL STRUCTURES. 2 List seq, sel, rep

  3. Sequential execution von Neumann The design of computers in which program instructions are stored in memory along with the data processed by the program is known as the architecture. A special register, called the instruction counter (IC), stores the address 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: Named after mathematician/physicist John von Neumann (see Ch.1, p. 8) Fetch the instruction whose address is in the IC Decode it to find the opcode and the operands Execute the operation IC++ (unless the IC is changed in some other way) 3 Diagram: IC, memory, CPU

  4. Note: A compound statement is a single statement and can thus be used any place a statement is needed .  In C++, a list of statements enclosed in curly braces { Statement1 Statement2 ... StatementN } The last step (IC++) indicates that the default manner of executing statements is sequential. STYLE TIP Indent& align the statements they enclose. is known as a compound statement (or block). It is a statement that produces sequential execution of the statements enclosed by the { and }. 4 Nested blocks; Pascal: BEGIN…END

  5. Scope A variable declared within a block is called a local variable. It exists (has memory allocated to it) only from its declaration to the end of the block. We say that its scope extends from its declaration to the end of the block. This is one of several scope rules. Others will be described later. For example, in the code ... cin >> item; while (item != -999) { int i = 0; ... cin >> item; i++; }cout << "Value of i = " << i; the last line won't compile because local variable iis out of scope. The "lifetime" of i ends at the }. 5 Move int I = 0-; Will have blocks inside blocks

  6. optional 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 condition (a boolean expression): The C++ if statement is a statement that causes selective execution, allowing a program to choose exactly one of two statements and execute it. if (Condition) Statement1 else Statement2 Note again:An if statement is a single state-ment, even if it extends over many lines. 6 Statements can be blocks

  7. T Condition Statement F The Simple if The C++ if statement has several different forms. The first form has no else or Statement2, and iscalled the simple if: if (Condition) Statement If Condition is true, Statement is executed; otherwise Statement is skipped. 7 Proceed or bypass Some programmers use else;

  8. // if value is negative, make it positive if (value < 0) value = -value; Examples: // Display date in mm/dd/yyyy format if (month < 10) cout << 0; cout << month << '/'; if (day < 10) cout << 0; cout << day << '/' << year << endl; 8 Efficient alternative to abs(value); endl

  9. cout is buffered;cerr is not. Examples showing Statement can be a compound statement: // if a < b, interchange a and b (integers)if (a < b) { int temp = a; a = b; b = temp; } Common Alternative Style: if (a < b){int temp = a; a = b; b = temp; } // Stop program if a is 0 // (in quadratic equation solver) if (a == 0) { cerr << "*** Coefficient of x^2 cannot be 0 ***\n"; exit(1);// Stop execution & return 1 to OS } Lab 4:Exer. 4.3 9 Visual aligns either format; User-friendly assert

  10. T F Condition Statement1 Statement2 The Two-Branch if In the second form of if, the else and Statement2 are present: STYLE TIP Align if and else and indent & align the statements in each part. if (Condition) Statement1 else Statement2 If Condition is true, Statement1 is executedand Statement2 is skipped; otherwise Statement1 is skipped and Statement2is executed. 10

  11. 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"; Example: 11

  12. The Multi-branch if if (Cond1) Stmt1 else if (Cond2) Stmt2 ... else if (CondN) StmtN else StmtN+1 The final form of the if statement is: STYLE TIP Align if, else ifs, and else and indent & align the statements in each part. Exactly one of the statementsStmti will be selected and executed, namely, the one corresponding to the first Condi that is true. 12

  13. StmtN StmtN+1 Stmt1 Stmt2 Stmt3 The intent is to implement a multi-alternative selection structure of the following form, where exactly one of the alternatives is selected and executed: F F F F T T T T 13 Click switch

  14. Cond1 F T Cond2 Stmt1 T F . . . Stmt2 CondN T F StmtN StmtN+1 Actually, however, it implements a "waterfall" selection structure of the following form: 14

  15. if (Cond1) Stmt1 else if (Cond2) Stmt2 else if (Cond3) Stmt3 ... else if (CondN) StmtN else StmtN+1 And it is treated by the compiler as a sequence of nested ifs in which each else clause (except the last) is another if-else statement: 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 move if up

  16. if (Cond1) Stmt1 else if (Cond2) Stmt2 ... else if (CondN) StmtN else StmtN+1 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. 16

  17. 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

  18. Note the simple conditions; we don't need (score <= 100 && score >= 90)(score < 90 && score >= 80)(score < 80 && score >= 70) (score < 70 && score >= 60) Do you understand why? ... or the preferred if-else-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'; Here's an example of program efficiency — not doing unnecessary computations. 18 menu processing - Lab 4

  19. 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 condition. 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 for, while, do-while

  20. Causes termination — think "while this is true, do the following" Usually modifies something each time through the loop Does theinitialization for (InitializerExpr; LoopCondition; ModifierExpr) Statement Need not all be on one line 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. Compared to for statements in other programming languages, C++'s has an unusual syntax. 20 for (int I = 1; I <= 10; i++)

  21. InitializerExpr F LoopCondition T Statement ModifierExpr The for Loop for (InitializerExpr; LoopCondition; ModifierExpr) Statement Statement will be executed so long as LoopConditionis true. Statement is often called the body of the loop. STYLE TIP Indent and align the statements in the body of the loop. 21

  22. false InitializerExpr F LoopCondition T Statement ModifierExpr for (InitializerExpr; LoopCondition; ModifierExpr) Statement true Each execution of LoopCondition Statement ModifierExpr is called one repetition oriteration of the loop. 22

  23. InitializerExpr F LoopCondition T Statement ModifierExpr for (InitializerExpr; LoopCondition; ModifierExpr) Statement When LoopCondition becomes false,control proceeds to the statement following the loop. Note: if the LoopCondition is initially false, then the body of the loop willnot be executed. For this reason this is called a pretest loop. 23

  24. Declare and initialize the loop- control variable Inc-/dec-rement loop-control variable Check if loop-control variable has gone through all its values InitializerExpr F LoopCondition T Statement ModifierExpr count += 2 Counting The "normal" use of the for loop is to count: int limit; cin >> limit; for (int count = 1; count <= limit; count++) { cout << count << endl; } Could omit { }; loop body contains a single statement Output (suppose limit = 5): 1 2 3 4 5 1 What if limit is 1? ScopeRule no output limit is 0? How get 1, 3, 5, . . . ? 24 Scope: Need count after loop? Move initializer up

  25. Nested Loops Loops can also be nested: for (int val1 = 1; val1 <= limit1; val1++) { for (int val2 = 1; val2 <= limit2; val2++) { cout << val1 << '*' << val2 << " = " << val1 * val2 << endl; } } Could omit { } since each loop body contains a single statement Output (suppose limit1 = 2, limit2 = 3): 1*1 = 1 1*2 = 2 1*3 = 3 2*1 = 2 2*2 = 4 2*3 = 6 25 Table output

  26. Input Loops There are two different types of input loops: • Counting 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 betwe en the mean and 50% is the C- cutoff. 50% is the D- cutoff. 26

  27. 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

  28. 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-: " << (100 + average) /2 << "%\n" << "B-: " << average << "%\n" << "C-: " << (average + 50) / 2 << "%\n" << "D-: " << 50 << "%\n"; } 28

  29. Execution of our example program: Program finds letter grade cutoffs for a test. Enter number of scores: 5 Enter a score: 77 Enter a score: 88 Enter a score: 66 Enter a score: 77 Enter a score: 99 A-: 90.7% B-: 81.4% C-: 65.7% D-: 50% 29

  30. The second kind of input loop: 2. Sentinel 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 whileloop is commonly used in many programming languages. -This method requires the availability of an appropriate sentinel value. 30 Second part of lab

  31. F Condition T Statement The while Loop Pattern: while (Condition) Statement Statement can be either a single or a compound statement, but is almost always compound. Repetition continues so long as Condition is true. 31

  32. F Condition T Statement Using while for an Input Loop Need the first inputvalue so it can becompared with sentinel Pattern: Prompt for first valueRead value while (value != sentinel){ Process the value Prompt for another valueRead value} Get thenext value 32

  33. 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

  34. sentinel cout << "Enter a test score (-1 to quit): "; cin >> score; while (score >= 0) { count++; 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); } // Compute and display letter grade cutoffs. cout << "\nA-: " << (100 + average) /2 << "%\n" << "B-: " << average << "%\n" << "C-: " << (average + 50) / 2 << "%\n" << "D-: " << 50 << "%\n"; } 34

  35. 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

  36. Textbook: Chap. 1, pages 8-9 In other early computers, the instructions were stored outside the machine on punched cards or some other medium and were transferred into the machine one at a time for interpretation and execution. In 1945, Princeton mathematician John von Neumann wrote “First Draft of a Report on the EDVAC (Electronic Discrete Variable Automatic Computer)” computer in which he described a scheme that required program instructions to be stored internally before execution. This led to his being credited as the inventor of the stored-program concept. The architectural design he described is still known as the von Neumann architecture. The advantage of executing instructions from a computer’s memory rather than directly from a mechanical input device is that it eliminates time that the computer must spend waiting for instructions. Instructions can be processed more rapidly and more importantly, they can be modified by the computer itself while computations are taking place. The introduction of this scheme to computer architecture was crucial to the development of general-purpose computers.

  37. F Condition T Statement Using while for an Input Loop while (value != sentinel){ Prompt for a valueRead value Process the value } 37

More Related