1 / 36

Chapter 4: Repetition Structures: Looping

Chapter 4: Repetition Structures: Looping. Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and Elizabeth Drake. 4.1 An Introduction to Repetition Structures: Computers Never Get Bored.

Download Presentation

Chapter 4: Repetition Structures: Looping

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. Chapter 4:Repetition Structures: Looping Extended Prelude to Programming Concepts & Design, 3/e byStewart Venit and Elizabeth Drake

  2. 4.1 An Introduction to Repetition Structures: Computers Never Get Bored A loop is a block of code that, under certain conditions will be executed repeatedly. Repeat Prompt for and input a number, Num Write NumUntil Num = 0Write “Done” • The bodyof the loop is executed repeatedly until the user enters a 0. At that point the loop is exited, and the statement that follows the loop is executed. • Note the indentation.

  3. Flowchart for a Simple Loop

  4. Beware of the Infinite Loop! The following loop will repeat continually. Can you see why? Repeat Prompt: “Enter a positive number:“ Input Number Set ComputerNumber = Number + 1 Write Number Until Number > ComputerNumber Write “Done”

  5. How to Know When To Quit • Be sure to tell the user how to leave the loop. • Example: Add a line, as shown, to the example given so the user knows how to stop entering numbers! Repeat Prompt: “Enter a number” Prompt: “Enter 0 to end the program” Input Num Write NumUntil Num = 0Write “Done”

  6. Relational Operators (review from Chapter 3) Relational operators are the symbols used in the condition to be evaluated in If statements: = equal to <> not equal to < less than > greater than <= less than or equal to >= greater than or equal to

  7. Examples (review from Chapter 3) Given: A = 23, B = 16 Then: A > B is true A < B is false A >= Bis true A <= Bis false A <> B is true A = B is false

  8. Comparison vs. Assignment Operators (review from Chapter 3) The equals sign (=) in this text may have two different meanings. The difference is very significant. As an assignment operator, the equals sign sets the value of an expression on the right side to the variable on the left side. As a comparison operator, the equals sign asks the question, “Is the value of the variable on the left side the same as the value of the expression, number, or variable on the right side?” Many programming languages distinguish between these two operators as follows: • a single equals sign (=) signifies the assignment operator • a double equals sign (==) signifies the comparison operator This is demonstrated in the examples that follow in the next slides.

  9. The Assignment Operator (review from Chapter 3) Given: A = 14, B = 27 In programming code, the assignment statement: A = B sets the value of B to the variable A. In other words, after this statement is executed, both A = 17 and B= 17. In this case, the equals sign is used as an assignment operator.

  10. The Comparison Operator (review from Chapter 3) Given: A = 14, B = 27 Using the relational operators, the statement: A == B is a comparison. This statement asks the question, “Is the value of A the same as the value of B?” In this case, since A and B have different values, the answer is “no” and the statement would result in a value of False. In this text, we often use the one symbol (=) to represent both assignment and comparison operators and rely on the context to make the meaning clear.

  11. Logical Operators (review from Chapter 3) • Logical operators are used to connect simple conditions into a more complex condition called a compound condition. • The simple conditions each contain one relational operator. • Using compound conditions reduces the amount of code that must be written.

  12. The AND Operator (review from Chapter 3) • A compound condition consisting of two simple conditions joined by an AND is true only if both simple conditions are true. It is false if even one of the conditions is false. The statement: If (X > 5) AND (X < 10) Then … is true only if X is 6, 7, 8, or 9. It has to be both greater than 5 and less than 10 at the same time.

  13. TheOROperator (review from Chapter 3) • A compound condition consisting of two simple conditions joined by an ORis true if even one of the simple conditions is true. It is false only if both are false. For example: If (Response =“Y”) OR (Response =“y”) Then … • This is true if Responseis uppercase or lower case y. For the above condition to be false, Responsewould have to be something other than either ‘Y’ or ‘y’.

  14. The NOT Operator • ANDand OR affect 2 simple conditions. • NOT affects only one condition. If you need to negate more than one simple condition, you will need more than one NOT. • A condition with the NOT operator is true only if the condition is false. NOT( A < B) is true only if B is greater than or equal to A. If ( X > 100) AND NOT ( X = Y) Then… is true only if X is greater than 100 but not equal to the value of Y.

  15. Truth Tables forOR, AND, and NOT Operators

  16. Pre-test and Post-Test Loops This is a post-test loop. The test condition occurs after the body of the loop is executed. Repeat Prompt for and input a number, Num Write NumUntil Num = 0Write “Done” This is a pre-test loop. The test condition appears at the top, before the body of the loop is executed the first time. Input Num While Num <> 0 Write Num Input Num End While

  17. Flowcharts for Pre-test and Post-Test Loops

  18. Trace A Loop(Walk through the loop manually) • It is impossible to see what a loop is doing without tracing it to see how it works. Suppose the user enters 3, 1, -1. Input Number While Number > 0 Write Number ^ 2 Input Number End While • NumberOutput • 3 9 • 1 1 • -1

  19. Counter-controlled Loops • The body of the loop is executed a fixed number of times (Ntimes) where N is known prior to entering the loop for the first time.Write “Enter a positive integer:” Input NSet Count = 1While Count <= N Write Count, Count ^ 2 Set Count = Count + 1End While If the user enters 4: N = 4 Count Output 1 1 1 2 2 4 3 3 9 4 4 16

  20. Counter-controlled Loops • Most programming languages contain a statement that makes is easy to construct a counter-controlled loop. ForCounter= InitialValue Step Increment To LimitValue Body of loop … … … End For

  21. Examples: 1. For Count = 1 Step 1 To 5 Write Count, Count ^ 2 End For 2. For N = 1 Step 2 To 20 Write N End For CountOutput 1 1 1 2 2 4 3 3 9 4 4 16 5 5 25 NOutput 1 1 3 3 5 5 … 17 17 19 19

  22. Countdown… A counter can count up or down, by any increment or decrement. For example: For Count = 21 Step -3 To 6 Write Count End For CountOutput 21 21 18 18 15 15 12 12 9 9 6 6

  23. Sentinel controlled loop example Suppose that the input data for a program that computes employee salaries consists of the number of hours worked and the rate of pay: Write “Enter the hours worked” Write “Enter –1 when you are done: Input Hours While hours <> -1 Write “Enter the rate of pay.” Input Rate Set Salary = Hours * Rate Write Hours, Rate, Salary Write “Enter the hours worked.” Write “Enter –1 when you are done.” Input Hours End While

  24. The results, given test data shown below, are given in the Trace box ----------------- Test Data Employee 1: Hours = 40 Rate of Pay = $10 Employee 2: Hours = 38 Rate of Pay = $12 Trace (walkthrough) Output: Enter the hours worked Enter –1 when you are done. 40 Enter the rate of pay 10 400 40 10 Enter the hours worked Enter –1 when you are done. 38 Enter the rate of pay 12 456 38 12 Enter the hours worked Enter –1 when you are done. -1 Sentinel controlled loop example continued

  25. How many beans will be displayed? Set beans = 4 Set Count = 1 While Count < beans Write “bean” Set Count = Count + 1 End While How many beans will be displayed? Set beans = 4 Set Count = 0 While Count < beans Write “bean” Set Count = Count + 1 End While Use the Test Condition Carefully!

  26. How many beans will be displayed? Set beans = 4 Set Count = beans While Count >= 0 Write “bean” Set Count = Count - 1 End While How many beans will be displayed? Set beans = 4 Set Count = 5 While Count < beans Write “bean” Set Count = Count - 1 End While Use the Test Condition Carefully!

  27. Data Validation • Loops can be used to validate data. • Check that a number is within a specified range. • Check that the user has entered a valid response to a prompt.

  28. Data Validation continued Use a loop to check that user input is valid: Write “Enter number of widgets you want:” Input widget While widget < 0 Write “Enter 0 or a positive number:” Input widget End While Write “You want to buy”, widget, “ widgets.”

  29. TheInt()Function • Int(X) converts X into an integer • X can be a number, a variable, or an expression Int(6) = 6 Int(-457.2376) = -457 • IfX = 234.42: Int(X) = 234 Int(X+ 6) = 240

  30. Use theInt()Function for Data Validation This program segment checks to ensure that the user enters an integer before displaying all the numbers from 1 up to the number selected. Repeat Write “Enter an integer, greater than 0:” Input MaxValue Until Int(MaxValue) = MaxValue For Count = 1 Step 1 To MaxValue Write Count End For

  31. Breaking Out … of a Loop It is possible to break out of a loop early if the user has entered a value that might cause an error or if the user enters a required response. In this example, a “secret number” has been stored in a variable namedsecret. Write “Guess the secret number in 5 tries or less!“ For Count = 1 Step 1 To 5 Write “Enter your guess: “ Input Guess If Guess = secret Then Write “You guessed it!” Else Write “Try again” End If End For

  32. Nested Loops • A loop may be contained entirely within another loop. For OutCount = 1 Step 1 To 2 For InCount = 1 Step 1 to 3 Write “Outer:”, OutCount, “Inner:”, InCount End For (Incount) Write End For (OutCount) • Trace the Nested Loop • Outer:1 Inner:1 • Outer:1 Inner:2 • Outer:1 Inner:3 • Outer:2 Inner:1 • Outer:2 Inner:2 • Outer:2 Inner:3

  33. Nesting other Kinds of Loops • Any style of loop may be nested. Each nested loop must be indented to indicate which statements are controlled by which looping construct. Repeat Other code here While <condition> More code here End While Until <condition>

  34. Pseudocode Language (Ch 4) In this chapter we added several types of repetition structures (loops). While loopsNested For loops: While condition ForI = X Step Y To Z do something ForJ = A Step B To C End While do something End For(J) Repeat … UntilEnd For (I) Repeat do something Until condition For loops ForCounter= InitialValue StepIncrementTo LimitValue do something End For

  35. Pseudocode Language (Ch 4) Previous pseudocode: InputAssignment InputVariable SetVariable= 10 Output Write “literal text”, Variable Arithmetic Operations ( ) ^ * / % + - Relational OperatorsLogical Operators = <> < > >= <= AND OR NOT

  36. Pseudocode Language (Ch 4) Previous pseudocode Create a moduleCall a sub-module ModuleName Call ModuleName content End Selection If-Then-Else StructureCase Structure If condition Then Select Case of something do something Case: X Else do something do something else Case: Y End If do something Default: do something End Case

More Related