1 / 64

C++ Programming I Lecture 3

C++ Programming I Lecture 3. MIS160 Instructor – Larry Langellier. Outline 2.14 The for Repetition Structure 2.15 Examples Using the for Structur e

Download Presentation

C++ Programming I Lecture 3

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. C++ Programming I Lecture 3 MIS160 Instructor – Larry Langellier

  2. Outline 2.14 The for Repetition Structure 2.15 Examples Using the for Structure 2.16 The switch Multiple-Selection Structure2.17 The do/while Repetition Structure 2.18 The break and continue Statements 2.19 Logical Operators 2.20 Confusing Equality (==) and Assignment (=) Operators 2.21 Structured-Programming Summary Lecture 3 - Control Structures (cont.)

  3. The for Repetition Structure • The general format when using for loops is for ( initialization; LoopContinuationTest; increment ) statement • Example: for( int counter = 1; counter <= 10; counter++ ) cout << counter << endl; • Prints the integers from one to ten No semicolon after last statement

  4. The for Repetition Structure • The for loop executes a section of code a fixed number of times • Example – fordemo.cpp (quick run through) • Syntax: #1: for (initexpr; testexpr; increxpr) statement; #2 : for (initexpr; testexpr; increxpr) { statement1; statement2; statement3; }

  5. The for Repetition Structure for (j=0; j<15; j++) cout << j * j << “ “; • There are three expressions involving the loop variable (j): • Initialization expression: j = 0 • Test expression: j < 15 • Increment expression: j++ • The “loop body” is the statement (or statements) executed each time through the loop

  6. The for Repetition Structure • Initialization expression: j = 0; • Executed only one time – at the beginning, set the starting value of the loop/counter variable • Test expression: j < 15; • Evaluates each time through the loop • If the value is true (non-zero), execute the loop body • If the value is false (zero), exit the loop and proceed to the next statement AFTER the loop body • Increment Expression: j++ • Evaluates each time through the loop AFTER the loop body is executed

  7. The for Repetition Structure • For loops can usually be rewritten as while loops: initialization; while ( loopContinuationTest){ statement increment; } • Initialization and increment as comma-separated lists for (int i = 0, j = 0; j + i <= 10; j++, i++) cout << j + i << endl; • Separate the different expressions with commas • Only one test expression allowed • Can also leave out some (or all) of the expressions • Example – factor.cpp • Variables defined in for statements • for (int j=numb; j>0; j--)

  8. 1 // Fig. 2.20: fig02_20.cpp 2 // Summation with for 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 int main() 9 { 10 int sum = 0; 11 12 for ( int number = 2; number <= 100; number += 2 ) 13 sum += number; 14 15 cout << "Sum is " << sum << endl; 16 17 return 0; 18 } Examples Using the for Structure • Program to sum the even numbers from 2 to 100 Sum is 2550

  9. Just Do It! Suppose you give a dinner party for six guests, but your table seats only four. In how many ways can four of the six guests arrange themselves at the table? Any of the six guests can sit in the first chair. Any of the remaining five can sit in the second chair, and so on. The number of possible arrangements of six guests in four chairs is 6*5*4*3, which is 360. Write a program that calculates the number of possible arrangements for any number of guests and any number of chairs. Don’t get too complicated - a simple for loop should do it.

  10. Sample Pseudocode Get the number of guests and the number of chairs from the user If there are more chairs than guests Output an error message Else For each chair Number of Arrangements *= number of remaining guests Print number of arrangements

  11. Sample Solution // permu.cpp #include <iostream> using std::cout; using std::cin; using std::endl; #include <process.h> // for exit() int main() { int guests, chairs, arrangements=1; cout << "Enter number of guests: "; cin >> guests; cout << "Enter number of chairs: "; cin >> chairs; if(guests < chairs) { cout << "Number of guests must be greater " << "than or equal to number of chairs"; exit(1); } for(int c=0; c<chairs; c++) arrangements *= (guests - c); cout << "number of arrangements is " << arrangements << endl; return 0; }

  12. true false true false . . . true false case a action(s) case z action(s) case b action(s) break break break default action(s) case b case a case z The switch Multiple-Selection Structure • switch • Useful when variable or expression is tested for multiple values • Consists of a series of case labels and an optional default case

  13. The switch Multiple-Selection Structure • Used to execute code based on the value of an expression • Syntax: switch (variable) { casevalue1: statement1; statement2; break; casevalue2: statement3; statement4; break; default: statement5; statement6; }

  14. The switch Multiple-Selection Structure • Assign a value to the switch variable before entering the switch • When a value matches a constant in a case statement, the following statements will be executed until a break is reached • The break statement causes the entire switch statement to exit • Without the break, control passes to the statements for the next case

  15. The switch Multiple-Selection Structure • If no cases are matched, execution continues with the next statement following the case • The default gives the switch a way to execute a block of code if none of the case constants are matched. • Example – platters.cpp • Example – adswitch.cpp

  16. 1 // Fig. 2.22: fig02_22.cpp 2 // Counting letter grades Notice how the case statement is used 3 #include <iostream> 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 int main() 10 { 11 int grade, // one grade 12 aCount = 0, // number of A's 13 bCount = 0, // number of B's 14 cCount = 0, // number of C's 15 dCount = 0, // number of D's 16 fCount = 0; // number of F's 17 18 cout << "Enter the letter grades." << endl 19 << "Enter the EOF character to end input." << endl; 20 21 while ( ( grade = cin.get() ) != EOF ) { 22 23 switch ( grade ) { // switch nested in while 24 25 case 'A': // grade was uppercase A 26 case 'a': // or lowercase a 27 ++aCount; 28 break; // necessary to exit switch 29 30 case 'B': // grade was uppercase B 31 case 'b': // or lowercase b 32 ++bCount; 33 break; 34 1. Initialize variables 2. Input data 2.1 Use switch loop to update count

  17. 35 case 'C': // grade was uppercase C 36 case 'c': // or lowercase c 37 ++cCount; breakcausesswitchto end and the program continues with the first statement after theswitchstructure. 38 break; 39 40 case 'D': // grade was uppercase D Notice the default statement. 41 case 'd': // or lowercase d 42 ++dCount; 43 break; 44 45 case 'F': // grade was uppercase F 46 case 'f': // or lowercase f 47 ++fCount; 48 break; 49 50 case '\n': // ignore newlines, 51 case '\t': // tabs, 52 case ' ': // and spaces in input 53 break; 54 55 default: // catch all other characters 56 cout << "Incorrect letter grade entered." 57 << " Enter a new grade." << endl; 58 break; // optional 59 } 60 } 61 62 cout << "\n\nTotals for each letter grade are:" 63 << "\nA: " << aCount 64 << "\nB: " << bCount 65 << "\nC: " << cCount 66 << "\nD: " << dCount 67 << "\nF: " << fCount << endl; 68 69 return 0; 70 } 2.1 Use switch loop to update count 3. Print results

  18. Enter the letter grades. Enter the EOF character to end input. a B c C A d f C E Incorrect letter grade entered. Enter a new grade. D A b Totals for each letter grade are: A: 3 B: 2 C: 3 D: 2 F: 1 Program Output

  19. Just Do It! Create a four-function calculator for fractions. Use the switch statement. Here are the formulas for the four arithmetic operations applied to fractions: Addition: a/b + c/d = (a*d + b*c)/(b*d) Subtraction: a/b – c/d = (a*d - b*c)/(b*d) Multiplication: a/b * c/d = (a*c)/(b*d) Division: a/b / c/d = (a*d)/(b*c) The user should type the first fraction, an operator, and a second fraction. The program should display the result.

  20. Sample Pseudocode Get two fraction and the operator from the user If op is addition num = n1*d2 + d1*n2 den = d1 * d2 op is subtraction num = n1*d2 – n2*d1 den = d1 * d2 op is multiplication num = n1 * n2 den = d1 * d2 op is division num = n1 * d2 den = n2 * d1 Print the answer

  21. Sample Solution // frac4fun.cpp // four-function calculator for fractions #include <iostream> using std::cout; using std::cin; using std::endl; int main() { long num1, den1, num2, den2, num3, den3; char dummy, op; cout << "\n\nEnter fraction, operator, fraction"; cout << "\nform 3/4+3/8 (or 0/1+0/1 to exit): "; cin >> num1 >> dummy >> den1; cin >> op; cin >> num2 >> dummy >> den2; switch (op) { case '+': // (a*d+b*c) / (b*d) num3 = num1 * den2 + den1 * num2; den3 = den1 * den2; break; case '-': // (a*d-b*c) / (b*d) num3 = num1 * den2 - den1 * num2; den3 = den1 * den2; break;

  22. Sample Solution (cont.) case '*': // (a*c) / (b*d) num3 = num1 * num2; den3 = den1 * den2; break; case '/': // (a*d) / (b*c) num3 = num1 * den2; den3 = den1 * num2; break; default: cout << "No such operator"; } cout << "Answer = " << num3 << '/' << den3 << endl; return 0; }

  23. true false action(s) condition The do/while Repetition Structure • The do/while repetition structure is similar to the while structure, • Condition for repetition tested after the body of the loop is executed • Format: do { statement } while ( condition ); • Example (letting counter = 1): do { cout << counter << " "; } while (++counter <= 10); • This prints the integers from 1 to 10 • All actions are performed at least once.

  24. The do/while Repetition Structure • Syntax 1 do statement; while (test_expression); • Syntax 2 do { statement1; statement2; statement3; } while (test_expression); • Example – divdo.cpp

  25. The break and continue Statements • break • Causes immediate exit from a while, for, do/while or switch structure • Program execution continues with the first statement after the structure • Common uses of the break statement: • Escape early from a loop • Skip the remainder of a switch structure

  26. The break and continue Statements • continue • Skips the remaining statements in the body of a while, for or do/while structure and proceeds with the next iteration of the loop • In while and do/while, the loop-continuation test is evaluated immediately after the continue statement is executed • In the for structure, the increment expression is executed, then the loop-continuation test is evaluated

  27. When to Use Which Loop • for – When you know in advance how many times the loop should execute • while – When you don’t know how many times the loop should execute in advance and the loop may not need to execute even once • do/while – When you’re sure the loop should execute at least once, but aren’t sure in advance how many times it should execute

  28. Just Do It! The process of finding the largest number (I.e. the maximum of a group of numbers) is used frequently in computer applications. Create a program that will allow you to enter a test score for each student. After you write pseudocode, write a C++ program that inputs scores for students until a –1 is entered. Determine and print the highest test score. Use a do/while loop in your solution. Hint: You may wish to use two variables, as follows: score: The current score input to the program. largest: The largest number found so far.

  29. Sample Pseudocode Input a test score If the score is not –1 do if the new score is bigger than the largest largest = new score Prompt for another score while the score is not –1 Print the largest

  30. Sample Solution // highscore.cpp // determines the highest test score and displays it #include <iostream> using std::cout; using std::cin; using std::endl; int main() { int score = 0, largest = 0; cout << "\nEnter a test score: "; cin >> score; //get initial number if ( score > -1 ) // is there a better solution? do { if ( score > largest ) largest = score; cout << "\nEnter a test score: "; cin >> score; //get next number } while (score != -1); cout << "The highest score was " << largest << endl; return 0; }

  31. Logical Operators • && (logical AND) • Returns true if both conditions are true • || (logical OR) • Returns true if either of its conditions are true • ! (logical NOT, logical negation) • Reverses the truth/falsity of its condition • Returns true when its condition is false • Is a unary operator, only takes one condition • Logical operators used as conditions in loops Expression Result true && false falsetrue || false true!false true • Examples – advenand.cpp and advenor.cpp

  32. Confusing Equality (==) and Assignment (=) Operators • These errors are damaging because they do not ordinarily cause syntax errors. • Recall that any expression that produces a value can be used in control structures. Nonzero values are true, and zero values are false • Example: if ( payCode == 4 ) cout << "You get a bonus!" << endl; • Checks the paycode, and if it is 4 then a bonus is awarded • If == was replaced with = if ( payCode = 4 ) cout << "You get a bonus!" << endl; • Sets paycode to 4 • 4 is nonzero, so the expression is true and a bonus is awarded, regardless of paycode.

  33. Confusing Equality (==) and Assignment (=) Operators • Lvalues • Expressions that can appear on the left side of an equation • Their values can be changed • Variable names are a common example (as in x = 4;) • Rvalues • Expressions that can only appear on the right side of an equation • Constants, such as numbers (i.e. you cannot write 4 = x;) • Lvalues can be used as rvalues, but not vice versa

  34. Operator Precedence • Unary !, ++, --highest • Arithmetic Multiplicative: *, /, % Additive: +, - • Relational Inequality: <, >, <=, >= Equality: ==, != • Logical And: && Or: || • Conditional ? : • Assignment =, +=, -=, /=, *=, %=lowest

  35. Structured-Programming Summary • Structured programming • Programs are easier to understand, test, debug and, modify. • Rules for structured programming • Only single-entry/single-exit control structures are used • Rules: 1) Begin with the “simplest flowchart”. 2) Any rectangle (action) can be replaced by two rectangles (actions) in sequence. 3) Any rectangle (action) can be replaced by any control structure (sequence, if, if/else, switch, while, do/while or for). 4) Rules 2 and 3 can be applied in any order and multiple times.

  36. Rule 3 Rule 3 Rule 3 Structured-Programming Summary Representation of Rule 3 (replacing any rectangle with a control structure)

  37. Structured-Programming Summary • All programs can be broken down into • Sequence • Selection • if, if/else, or switch • Any selection can be rewritten as an if statement • Repetition • while, do/while or for • Any repetition structure can be rewritten as a while statement

  38. Thinking About Objects • Case study • Substantial, carefully paced, complete design and implementation experience • Chapters 2 - 5 • Steps of an object-oriented design (OOD) using the UML • Chapters 6 & 7 • Implement elevator simulator using the techniques of object-oriented programming (OOP) • This is not an exercise • End-to-end learning experience

  39. Identifying the Classes in a Problem • Problem Statement (full text in book) • Company wants you to build a 2-floor elevator simulator • Clock that begins with zero seconds • Incremented every second, does not keep track of hours and minutes • Scheduler • Randomly picks two times when two people use the elevator (one on floor1, one on floor 2) • Each time is a random integer from 5 to 20, inclusive • When clock reaches earlier of two times, scheduler creates a person who hits appropriate floor button • Floor button automatically illuminates (no programming necessary) • Light turns off when button reset

  40. Simulation Details • Elevator Operation • Elevator starts with doors closed on floor 1 • Only moves when necessary

  41. Simulation Details (II) • Details • For simplicity, elevator and floor can hold one person • Scheduler verifies floor empty before creating a person on it • If floor occupied, scheduler delays creation of new person for one second. • After person walks onto floor, scheduler creates random time (5 to 20 seconds in future) for another person to walk onto the floor • When elevator arrives on floor, resets button and sounds bell (inside elevator) • Signals arrival to floor • Floor resets floor button, turns on elevator arrival light • Elevator opens door (floor door opens automatically, needs no programming) • Elevator passenger, if there is one, exits elevator • Floor large enough to allow person to wait while passenger exits elevator

  42. Simulation Details (III) • Person entering elevator • Presses elevator button (lights automatically, no programming necessary) • Button turns off when elevator reaches desired floor • Only two floors in building, so elevator needs only one button (to tell elevator to move to other floor) • Elevator closes door, begins moving to other floor • Person exits • If no one enters and other floor button not pushed, elevator stays on floor with doors closed • Timing • All activities that happen when elevator reaches a floor take zero time • The activities still occur sequentially (door opens before passenger exits)

  43. Simulation Details (IV) • Timing (continued) • Elevator takes 5 seconds to move between floors • Once per second, simulator provides time to scheduler and elevator • They use the time to determine what actions to take • Simulator • Should display messages on screen describing activities of system • Person pressing floor button, elevator arrival, clock ticking, person entering, etc. • Sample output on following slides

  44. Enter run time: 30 (scheduler schedules next person for floor 1 at time 5) (scheduler schedules next person for floor 2 at time 17) *** ELEVATOR SIMULATION BEGINS *** TIME: 1 elevator at rest on floor 1 TIME: 2 elevator at rest on floor 1 TIME: 3 elevator at rest on floor 1 TIME: 4 elevator at rest on floor 1 TIME: 5 scheduler creates person 1 person 1 steps onto floor 1 person 1 presses floor button on floor 1 floor 1 button summons elevator (scheduler schedules next person for floor 1 at time 20) elevator resets its button elevator rings its bell floor 1 resets its button floor 1 turns on its light elevator opens its door on floor 1 person 1 enters elevator from floor 1 person 1 presses elevator button elevator button tells elevator to prepare to leave floor 1 turns off its light elevator closes its door on floor 1 elevator begins moving up to floor 2 (arrives at time 10) Sample Simulation

  45. TIME: 6 elevator moving up TIME: 7 elevator moving up TIME: 8 elevator moving up TIME: 9 elevator moving up TIME: 10 elevator arrives on floor 2 elevator resets its button elevator rings its bell floor 2 resets its button floor 2 turns on its light elevator opens its door on floor 2 person 1 exits elevator on floor 2 floor 2 turns off its light elevator closes its door on floor 2 elevator at rest on floor 2 TIME: 11 elevator at rest on floor 2 TIME: 12 elevator at rest on floor 2 TIME: 13 elevator at rest on floor 2 Sample Simulation

  46. TIME: 14 elevator at rest on floor 2 TIME: 15 elevator at rest on floor 2 TIME: 16 elevator at rest on floor 2 TIME: 17 scheduler creates person 2 person 2 steps onto floor 2 person 2 presses floor button on floor 2 floor 2 button summons elevator (scheduler schedules next person for floor 2 at time 34) elevator resets its button elevator rings its bell floor 2 resets its button floor 2 turns on its light elevator opens its door on floor 2 person 2 enters elevator from floor 2 person 2 presses elevator button elevator button tells elevator to prepare to leave floor 2 turns off its light elevator closes its door on floor 2 elevator begins moving down to floor 1 (arrives at time 22) TIME: 18 elevator moving down TIME: 19 elevator moving down Sample Simulation

  47. TIME: 20 scheduler creates person 3 person 3 steps onto floor 1 person 3 presses floor button on floor 1 floor 1 button summons elevator (scheduler schedules next person for floor 1 at time 26) elevator moving down TIME: 21 elevator moving down TIME: 22 elevator arrives on floor 1 elevator resets its button elevator rings its bell floor 1 resets its button floor 1 turns on its light elevator opens its door on floor 1 person 2 exits elevator on floor 1 person 3 enters elevator from floor 1 person 3 presses elevator button elevator button tells elevator to prepare to leave floor 1 turns off its light elevator closes its door on floor 1 elevator begins moving up to floor 2 (arrives at time 27) TIME: 23 elevator moving up TIME: 24 elevator moving up TIME: 25 elevator moving up Sample Simulation

  48. TIME: 26 scheduler creates person 4 person 4 steps onto floor 1 person 4 presses floor button on floor 1 floor 1 button summons elevator (scheduler schedules next person for floor 1 at time 35) elevator moving up TIME: 27 elevator arrives on floor 2 elevator resets its button elevator rings its bell floor 2 resets its button floor 2 turns on its light elevator opens its door on floor 2 person 3 exits elevator on floor 2 floor 2 turns off its light elevator closes its door on floor 2 elevator begins moving down to floor 1 (arrives at time 32) TIME: 28 elevator moving down TIME: 29 elevator moving down TIME: 30 elevator moving down *** ELEVATOR SIMULATION ENDS *** Sample Simulation

  49. Analyzing and Designing the System • In the "Thinking about Objects" sections • Perform steps of an object-oriented design process for the elevator system • UML design for use with any OOAD process (many exist) • Rational Unified Process - popular method • We present our own simplified design process • Simulations • World portion: elements that belong to the world which we simulate • Elevator, floors, buttons, lights, etc • Controller portion: elements needed to simulate word • Clock and scheduler

  50. Use Case Diagrams • Project development • Developers rarely start with a detailed problem statement, as we are • This document usually result of object oriented analysis (OOA) • Interview people who will build and use system • Get a list of system requirements, which guide design • Our problem statement contains these requirements • Analysis phase - clearly state what system will do • Design phase - clearly state how we will construct a system to perform tasks identified in analysis phase.

More Related