1 Control Structures Outline Introduction Algorithms Pseudocode Control

  • Slides: 42
Download presentation
1 Control Structures Outline -Introduction -Algorithms -Pseudocode -Control Structures -if Selection Structure -if/else Selection

1 Control Structures Outline -Introduction -Algorithms -Pseudocode -Control Structures -if Selection Structure -if/else Selection Structure -while Repetition Structure -Formulating Algorithms: Case Study 1 (Counter-Controlled Repetition) -Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study 2 (Sentinel-Controlled Repetition) -Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study 3 (Nested Control Structures) 2003 Prentice Hall, Inc. All rights reserved.

2 Introduction • Before writing a program – Have a thorough understanding of the

2 Introduction • Before writing a program – Have a thorough understanding of the problem – Carefully plan your approach for solving it • While writing a program – Know what “building blocks” are available – Use good programming principles 2003 Prentice Hall, Inc. All rights reserved.

3 Algorithms • Computing problems – Solved by executing a series of actions (statements)

3 Algorithms • Computing problems – Solved by executing a series of actions (statements) in a specific order • Algorithm is a procedure determining – Actions to be executed – Order to be executed • Program control – Specifies the order in which statements are executed in a program 2003 Prentice Hall, Inc. All rights reserved.

4 Algorithms • Consider a program to calculate the factorial of a number: factorial-Algorithm

4 Algorithms • Consider a program to calculate the factorial of a number: factorial-Algorithm 1. Get the number. 2. To begin, set the factorial of the number to be one. 3. While the number is greater than one i. Set the factorial to be the factorial multiplied by the number. ii. Decrement the number. 4. Print out the factorial 2003 Prentice Hall, Inc. All rights reserved.

5 Pseudocode • Pseudocode – Artificial, informal language used to develop algorithms – Similar

5 Pseudocode • Pseudocode – Artificial, informal language used to develop algorithms – Similar to everyday English • Not executed on computers – Used to think out program before coding • Easy to convert into C++ program – Only executable statements • No need to declare variables // 1. 2. 3. find the average of n numbers get numbers sum = Add (numbers) average = sum/n 2003 Prentice Hall, Inc. All rights reserved.

6 Pseudocode factorial-pseudocode // find the factorial of an integer factorial = 1 while

6 Pseudocode factorial-pseudocode // find the factorial of an integer factorial = 1 while (number > 1) factorial = factorial * number = number -1 print factorial 2003 Prentice Hall, Inc. All rights reserved.

7 Control Structures • Sequential execution – Statements executed in the order they are

7 Control Structures • Sequential execution – Statements executed in the order they are written • Transfer of control – Next statement executed not next one in sequence • 3 control structures (Bohm and Jacopini) – Sequence structure • Programs executed sequentially by default – Selection structures • if, if/else, switch • e. g. , perform action if condition is true – Repetition structures • while, do/while, for 2003 Prentice Hall, Inc. All rights reserved.

8 Control Structures • C++ keywords – Cannot be used as identifiers or variable

8 Control Structures • C++ keywords – Cannot be used as identifiers or variable names 2003 Prentice Hall, Inc. All rights reserved.

9 Control Structures • Flowchart (an alternative to Pseudocode) – Graphical representation of an

9 Control Structures • Flowchart (an alternative to Pseudocode) – Graphical representation of an algorithm – Special-purpose symbols connected by arrows (flowlines) – Rectangle symbol (action symbol) • Any type of action – Oval symbol • Beginning or end of a program, or a section of code (circles) 2003 Prentice Hall, Inc. All rights reserved.

10 Control Structures Actions transitions 2003 Prentice Hall, Inc. All rights reserved.

10 Control Structures Actions transitions 2003 Prentice Hall, Inc. All rights reserved.

11 if Selection Structure • Selection structure – Choose among alternative courses of action

11 if Selection Structure • Selection structure – Choose among alternative courses of action – Pseudocode example: If student’s grade is greater than or equal to 60 Print “Passed” – If the condition is true • Print statement executed, program continues to next statement – If the condition is false • Print statement ignored, program continues – Indenting makes programs easier to read • C++ ignores whitespace characters (tabs, spaces, etc. ) • Note: C++ does not ignore white space characters in “” – Example: cout<<“welcome ton”; 2003 Prentice Hall, Inc. All rights reserved.

12 if Selection Structure • Translation into C++ If student’s grade is greater than

12 if Selection Structure • Translation into C++ If student’s grade is greater than or equal to 60 Print “Passed” if ( grade >= 60 ) cout << "Passed"; • Diamond symbol (decision symbol) – Indicates decision is to be made – Contains an expression that can be true or false • Test condition, follow path • if structure – Single-entry/single-exit 2003 Prentice Hall, Inc. All rights reserved.

13 if Selection Structure • Flowchart of pseudocode statement Guard condition if: single entry-single

13 if Selection Structure • Flowchart of pseudocode statement Guard condition if: single entry-single exit structure A decision can be made on any expression. zero - false nonzero - true 2003 Prentice Hall, Inc. All rights reserved.

14 if/else Selection Structure • if – Performs action if condition true. Otherwise, action

14 if/else Selection Structure • if – Performs action if condition true. Otherwise, action is skipped • if/else – Different actions if conditions true or false • Pseudocode if student’s grade is greater than or equal to 60 print “Passed” else print “Failed” • C++ code if ( grade >= 60 ) cout << "Passed"; else cout << "Failed"; 2003 Prentice Hall, Inc. All rights reserved.

15 if/else Selection Structure • Ternary conditional operator (? : ) – Three arguments

15 if/else Selection Structure • Ternary conditional operator (? : ) – Three arguments (condition, value if true, value if false) • Code could be written: cout << ( grade >= 60 ? “Passed” : “Failed” ); Condition Value if true Value if false Conditional expression with actions to execute • One can also write a conditional expression grade >= 60 ? cout << “Passed” : cout << “Failed”; which reads: if grade is greater than or equal to 60, cout<<“Passed”; otherwise, cout<<“Failed” 2003 Prentice Hall, Inc. All rights reserved.

16 if/else Selection Structure action state 2003 Prentice Hall, Inc. All rights reserved.

16 if/else Selection Structure action state 2003 Prentice Hall, Inc. All rights reserved.

17 if/else Selection Structure • Nested if/else structures – One inside another, test for

17 if/else Selection Structure • Nested if/else structures – One inside another, test for multiple cases – Once condition met, other statements skipped if student’s grade is greater than or equal to 90 Print “A” else if student’s grade is greater than or equal to 80 Print “B” else if student’s grade is greater than or equal to 70 Print “C” else if student’s grade is greater than or equal to 60 Print “D” else Print “F” 2003 Prentice Hall, Inc. All rights reserved.

18 if/else Selection Structure • Example (C++ code) if ( grade >= 90 )

18 if/else Selection Structure • Example (C++ code) if ( grade >= 90 ) cout << "A"; else if ( grade >= 80 ) cout << "B"; else if ( grade >= 70 ) cout << "C"; else if ( grade >= 60 ) cout << "D"; else cout << "F"; 2003 Prentice Hall, Inc. All rights reserved. // 90 and above // 80 -89 // 70 -79 // 60 -69 // less than 60

19 if/else Selection Structure • Example (C++ code) if ( grade >= 90 )

19 if/else Selection Structure • Example (C++ code) if ( grade >= 90 ) cout << "A"; else if ( grade >= 80 ) cout << "B"; else if ( grade >= 70 ) cout << "C"; else if ( grade >= 60 ) cout << "D"; else cout << "F"; // 90 and above // 80 -89 // 70 -79 // 60 -69 // less than 60 • This form of using if/else is more popular because it avoids deep indentation of the code 2003 Prentice Hall, Inc. All rights reserved.

20 if/else Selection Structure • Compound statement – Set of statements within a pair

20 if/else Selection Structure • Compound statement – Set of statements within a pair of braces if ( grade cout << else { cout << >= 60 ) "Passed. n"; "Failed. n"; "You must take this course again. n"; } – Without braces, cout << "You must take this course again. n"; will always be executed regardless of whether the grade is less than 60 or not. • Block – Set of statements within braces 2003 Prentice Hall, Inc. All rights reserved.

21 if/else Selection Structure • If you forget one or both of the braces,

21 if/else Selection Structure • If you forget one or both of the braces, a syntax or logic error may occur!! • Some programmers prefer to put the beginning and ending braces of a block before typing the individual statements within the braces if () { } else { } 2003 Prentice Hall, Inc. All rights reserved.

22 while -- Repetition Structure • Repetition structure – Action repeated while some condition

22 while -- Repetition Structure • Repetition structure – Action repeated while some condition remains true – Pseudocode while there are more items on my shopping list Purchase next item and cross it off my list – while loop repeated until condition becomes false: • Condition is “there are more items on my shopping list” • Action “Purchase next item and cross it off my list” • Action always repeated as long as condition remains true • Example int product = 2; while ( product <= 1000 ) product = 2 * product; 2003 Prentice Hall, Inc. All rights reserved. Each repetition of the while multiplies product by 2: àProduct takes values: 2, 4, 8, 16, 32, 64, 128, 256, 512 and 1024. When product is 1024, the condition becomes false

23 while -- Repetition Structure Merge and decision are distinguished by the number of

23 while -- Repetition Structure Merge and decision are distinguished by the number of incoming and outgoing arrows 2003 Prentice Hall, Inc. All rights reserved.

Formulating Algorithms (Counter-Controlled Repetition) • Counter-controlled repetition – Loop repeated until counter reaches certain

Formulating Algorithms (Counter-Controlled Repetition) • Counter-controlled repetition – Loop repeated until counter reaches certain value (predefined value) – Counter defines the number of times a group of statements will execute • Definite repetition – Number of repetitions known • Example A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz. 2003 Prentice Hall, Inc. All rights reserved. 24

Formulating Algorithms (Counter-Controlled Repetition) • Pseudocode for example: (total and grade are two variables)

Formulating Algorithms (Counter-Controlled Repetition) • Pseudocode for example: (total and grade are two variables) Set total to zero Set grade_counter to one While grade_counter is less than or equal to ten Input the next grade Add the grade into the total Add one to the grade_counter Set the class average to the total divided by ten Print the class average • Next: C++ code for this example 2003 Prentice Hall, Inc. All rights reserved. 25

1 2 3 // Fig. 4. 7: fig 04_07. cpp // Class average program

1 2 3 // Fig. 4. 7: fig 04_07. cpp // Class average program with counter-controlled repetition. #include <iostream> 4 5 6 7 using std: : cout; using std: : cin; using std: : endl; 8 9 10 11 12 13 14 15 // function main begins int main() { int total; // int grade. Counter; // int grade; // int average; // 16 17 18 19 20 program execution Outline Local variables (defined within the function). Must be defined before being used sum of grades input by user number of grade to be entered next grade value When variables are declared, they average of grades have to be initialized to the correct values. Otherwise, they may take // initialization phase any value (garbage value) last total = 0; // initialize total stored in the memory for that grade. Counter = 1; // initialize loop counter variable; hence will cause a logical error 2003 Prentice Hall, Inc. All rights reserved. 26

21 22 23 24 25 26 27 // processing phase while ( grade. Counter

21 22 23 24 25 26 27 // processing phase while ( grade. Counter <= 10 ) { cout << "Enter grade: "; cin >> grade; total = total + grade; grade. Counter = grade. Counter + 1; } 28 29 30 // termination phase average = total / 10; 31 32 33 34 35 36 37 } // // // loop 10 times prompt for input read grade from user add grade to total increment counter Outline // integer division grade was not initialized because the value provided by the user will total is upgraded when a new grade // display result replace whatever value the variable is entered. cout << "Class average is " << average << endl; The counter gets incremented each holds. time the loop executes. return 0; // indicate program ended successfully Eventually, the counter causes the loop to end. // end function main Enter grade: 98 Enter grade: 76 Enter grade: 71 Enter grade: 87 Enter grade: 83 Enter grade: 90 Enter grade: 57 2003 Prentice Hall, Inc. All rights reserved. 27

Formulating Algorithms (Sentinel-Controlled Repetition) • Suppose problem becomes: Develop a class-averaging program that will

Formulating Algorithms (Sentinel-Controlled Repetition) • Suppose problem becomes: Develop a class-averaging program that will process an arbitrary number of grades each time the program is run – Unknown number of students – How will program know when to end? • Sentinel value – Indicates “end of data entry” – Loop ends when sentinel input – Sentinel chosen so it cannot be confused with regular input • -1 in this cases (-1 cannot logically be a grade) • Sentinel controlled repetition is also known as indefinite repetition 2003 Prentice Hall, Inc. All rights reserved. 28

Formulating Algorithms (Sentinel-Controlled Repetition) • Top-down, stepwise refinement – Begin with pseudocode representation of

Formulating Algorithms (Sentinel-Controlled Repetition) • Top-down, stepwise refinement – Begin with pseudocode representation of top Determine the class average for the quiz – top is a single statement that conveys the overall function of the program – Divide top into smaller tasks, list in order Initialize variables Input, sum and count the quiz grades Calculate and print the class average 2003 Prentice Hall, Inc. All rights reserved. 29

Formulating Algorithms (Sentinel-Controlled Repetition) • Many programs have three phases – Initialization • Initializes

Formulating Algorithms (Sentinel-Controlled Repetition) • Many programs have three phases – Initialization • Initializes the program variables – Processing • Input data, adjusts program variables – Termination • Calculate and print the final results – Helps break up programs for top-down refinement 2003 Prentice Hall, Inc. All rights reserved. 30

Formulating Algorithms (Sentinel-Controlled Repetition) • Refine the initialization phase Initialize variables goes to Initialize

Formulating Algorithms (Sentinel-Controlled Repetition) • Refine the initialization phase Initialize variables goes to Initialize total to zero Initialize counter to zero • Processing Input, sum and count the quiz grades goes to Input the first grade (possibly the sentinel) While the user has not yet entered the sentinel Add this grade into the running total Add one to the grade counter Input the next grade (possibly the sentinel) 2003 Prentice Hall, Inc. All rights reserved. 31

Formulating Algorithms (Sentinel-Controlled Repetition) • Termination Calculate and print the class average goes to

Formulating Algorithms (Sentinel-Controlled Repetition) • Termination Calculate and print the class average goes to If the counter is not equal to zero Set the average to the total divided by the counter Print the average Else Print “No grades were entered” • Next: C++ program 2003 Prentice Hall, Inc. All rights reserved. 32

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 // Fig. 4. 9: fig 04_09. cpp // Class average program with sentinel-controlled repetition. #include <iostream> using Outline std: : cout; std: : cin; std: : endl; std: : fixed; #include <iomanip> // parameterized stream manipulators using std: : setprecision; // sets numeric output precision // function main begins program execution int main() Data type double used to represent { int total; // sum of grades decimal (floating-point) numbers. int grade. Counter; // number of grades entered int grade; // grade value 20 21 double average; 22 23 24 25 // initialization phase total = 0; // initialize total grade. Counter = 0; // initialize loop counter // number with decimal point for average 2003 Prentice Hall, Inc. All rights reserved. 33

26 27 28 29 30 31 32 33 34 35 36 37 38 39

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 // processing phase // get first grade from user cout << "Enter grade, -1 to end: " ; cin >> grade; Outline // prompt for input // read grade from user // loop until sentinel value read from user while ( grade != -1 )static_cast<double>() treats total as a double { total = total + grade; // add grade to total temporarily (casting). ( grade != -1 counter ) grade. Counter = grade. Counter +while 1; // increment total = total + grade; // add grade to total Required because dividing two integers yields an = grade. Counter + 1; cout << "Enter grade, -1 to end: grade. Counter " ; // prompt for input cin >> grade; } // end while integer (i. e. , truncates the remainder). // read next grade cout << "Enter grade, -1 to end: " ; grade. Counter is an int, but it gets promoted to cin >> grade; double. // termination phase // if user entered at least one grade. . . if ( grade. Counter != 0 ) { // calculate average of all grades entered average = static_cast< double >( total ) / grade. Counter; This cast operator has higher precedence than other unary operators. 2003 Prentice Hall, Inc. All rights reserved. 34

49 50 51 // display average with two digits of precision cout << "Class

49 50 51 // display average with two digits of precision cout << "Class average is " << setprecision( 2 ) << fixed << average << endl; 52 53 } // end if part of if/else 54 55 56 else // if no grades were entered, output appropriate message cout << "No grades were entered" << endl; 57 58 return 0; 59 60 Outline // indicate program ended successfully } // end function main setprecision(2)prints two digits past fixed forces output to print decimal point (rounded to fit precision). Enter grade, -1 to end: 75 in fixed point format (not scientific notation). Also, Enter grade, -1 to end: 94 forces trailing zeros and Programs that use this must include <iomanip> Enter grade, -1 to end: 97 decimal point to print. Enter grade, -1 to end: 88 Include <iostream> Enter grade, -1 to end: 70 Enter grade, -1 to end: 64 Enter grade, -1 to end: 83 Enter grade, -1 to end: 89 Enter grade, -1 to end: -1 Class average is 82. 50 2003 Prentice Hall, Inc. All rights reserved. 35

36 Nested Control Structures • Problem statement A college has a list of test

36 Nested Control Structures • Problem statement A college has a list of test results (1 = pass, 2 = fail) for 10 students. Write a program that analyzes the results. If more than 8 students pass, print "Raise Tuition". • Notice that – Program processes 10 results • Fixed number, use counter-controlled loop – Two counters can be used • One counts number that passed • Another counts number that fail – Each test result is 1 or 2 • If not 1, assume 2 (this assumption has consequences!) 2003 Prentice Hall, Inc. All rights reserved.

37 Nested Control Structures • Top level outline Analyze exam results and decide if

37 Nested Control Structures • Top level outline Analyze exam results and decide if tuition should be raised • First refinement Initialize variables Input the ten quiz grades and count passes and failures Print a summary of the exam results and decide if tuition should be raised • Refine Initialize variables (e. g. , counters) to Initialize passes to zero Initialize failures to zero Initialize student counter to one 2003 Prentice Hall, Inc. All rights reserved.

38 Nested Control Structures • Refine Input the ten quiz grades and count passes

38 Nested Control Structures • Refine Input the ten quiz grades and count passes and failures to While student counter is less than or equal to ten Input the next exam result If the student passed Add one to passes Else Add one to failures Add one to student counter 2003 Prentice Hall, Inc. All rights reserved.

39 Nested Control Structures • Refine Print a summary of the exam results and

39 Nested Control Structures • Refine Print a summary of the exam results and decide if tuition should be raised to Print the number of passes Print the number of failures If more than eight students passed Print “Raise tuition” • Program next 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 // Fig. 4. 11: fig 02_11. cpp // Analysis of examination

1 2 3 // Fig. 4. 11: fig 02_11. cpp // Analysis of examination results. #include <iostream> 4 5 6 7 using std: : cout; using std: : cin; using std: : endl; 8 9 10 11 12 13 14 15 16 // function main begins program execution initialization. int main() { // initialize variables in declarations int passes = 0; // number of passes int failures = 0; // number of failures int student. Counter = 1; // student counter int result; // one exam result 17 18 19 20 21 22 23 Outline Variable declarations and // process 10 students using counter-controlled loop while ( student. Counter <= 10 ) { // prompt user for input and obtain value from user cout << "Enter result (1 = pass, 2 = fail): " ; cin >> result; 24 2003 Prentice Hall, Inc. All rights reserved. 40

25 26 27 28 29 30 // if result 1, increment passes; if/else nested

25 26 27 28 29 30 // if result 1, increment passes; if/else nested in while if ( result == 1 ) // if/else nested in while passes = passes + 1; else // if result not 1, increment failures = failures + 1; 31 32 33 34 35 } // end while 36 37 38 39 // termination phase; display number of passes and failures cout << "Passed " << passes << endl; cout << "Failed " << failures << endl; 40 41 42 43 // if more than eight students passed, print "raise tuition" if ( passes > 8 ) cout << "Raise tuition " << endl; 44 45 return 0; 46 47 Outline // increment student. Counter so loop eventually terminates student. Counter = student. Counter + 1; // successful termination } // end function main 2003 Prentice Hall, Inc. All rights reserved. 41

Enter result Enter result Enter result Passed 6 Failed 4 (1 (1 (1 =

Enter result Enter result Enter result Passed 6 Failed 4 (1 (1 (1 = = = = = pass, pass, pass, 2 2 2 2 2 = = = = = fail): fail): fail): 1 2 2 1 1 1 2 Enter result (1 Enter result (1 Enter result (1 Passed 9 Failed 1 Raise tuition = = = = = pass, pass, pass, 2 2 2 2 2 = = = = = fail): fail): fail): 1 1 2 1 1 1 Outline 2003 Prentice Hall, Inc. All rights reserved. 42