Chapter 4 Repetition Structures Looping Extended Prelude to
- Slides: 36
Chapter 4: Repetition Structures: Looping Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and Elizabeth Drake Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
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 Num Until Num = 0 Write “Done” – The body of 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. 4 -2
Flowchart for a Simple Loop 4 -3
Beware of the Infinite Loop! The following loop will repeat continually. Can you see why? Repeat Prompt: “Enter a positive number: “ Input Number Set Computer. Number = Number + 1 Write Number Until Number > Computer. Number Write “Done” 4 -4
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 Num Until Num = 0 Write “Done” 4 -5
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 4 -6
Examples (review from Chapter 3) Given: A = 23, B = 16 Then: A A A > B is true < B is false >= B is true <= B is false <> B is true = B is false 4 -7
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. 4 -8
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. 4 -9
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. 4 -10
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. 4 -11
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. 4 -12
The OR Operator (review from Chapter 3) • A compound condition consisting of two simple conditions joined by an OR is 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 Response is uppercase or lower case y. For the above condition to be false, Response would have to be something other than either ‘Y’ or ‘y’. 4 -13
The NOT Operator • AND and 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. 4 -14
Truth Tables for OR, AND, and NOT Operators X Y X OR Y X AND Y NOT X true false true false false true 4 -15
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 Num Until Num = 0 Write “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 4 -16
Flowcharts for Pre-test and Post-Test Loops 4 -17
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 Number Output 3 9 1 1 -1 4 -18
Counter-controlled Loops • The body of the loop is executed a fixed number of times (N times) where N is known prior to entering the loop for the first time. Write “Enter a positive integer: ” Input N If the user enters 4: Set Count = 1 N=4 While Count <= N Count Output Write Count, Count ^ 2 1 1 1 Set Count = Count + 1 2 2 4 End While 3 3 9 4 4 16 4 -19
Counter-controlled Loops • Most programming languages contain a statement that makes is easy to construct a counter-controlled loop. For Counter = Initial. Value Step Increment To Limit. Value Body of loop … … … End For 4 -20
Examples: 1. Count Output 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 1 2 3 4 5 N 1 3 5 … 17 19 1 2 3 4 5 1 4 9 16 25 Output 1 3 5 17 19 4 -21
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 Count Output 21 18 15 12 9 6 4 -22
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 4 -23
Sentinel controlled loop example continued 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 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 4 -24
Use the Test Condition Carefully! How many beans will be displayed? Set beans = 4 Set Count = 1 While Count < beans Write “bean” Set Count = Count + 1 End While Set beans = 4 Set Count = 0 While Count < beans Write “bean” Set Count = Count + 1 End While 4 -25
Use the Test Condition Carefully! How many beans will be displayed? Set beans = 4 Set Count = beans While Count >= 0 Write “bean” Set Count = Count - 1 End While Set beans = 4 Set Count = 5 While Count < beans Write “bean” Set Count = Count - 1 End While 4 -26
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. 4 -27
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. ” 4 -28
The Int() 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 • If X = 234. 42: Int(X) = 234 Int(X + 6) = 240 4 -29
Use the Int() 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 Max. Value Until Int(Max. Value) = Max. Value For Count = 1 Step 1 To Max. Value Write Count End For 4 -30
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 named secret. 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 4 -31
Nested Loops • A loop may be contained entirely within another loop. For Out. Count = 1 Step 1 To 2 For In. Count = 1 Step 1 to 3 Write “Outer: ”, Out. Count, “Inner: ”, In. Count End For (Incount) Write Trace the Nested Loop End For (Out. Count) Outer: 1 Inner: 1 Outer: 1 Inner: 2 Outer: 1 Inner: 3 Outer: 2 Inner: 1 Outer: 2 Inner: 2 Outer: 2 Inner: 3 4 -32
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> 4 -33
Pseudocode Language (Ch 4) In this chapter we added several types of repetition structures (loops). While loops Nested For loops: While condition do something End While For I = X Step Y To Z For J = A Step B To C do something End For(J) End For (I) Repeat … Until Repeat do something Until condition For loops For Counter = Initial. Value Step Increment To Limit. Value do something End For 4 -34
Pseudocode Language (Ch 4) Previous pseudocode: Input Variable Assignment Set Variable = 10 Output Write “literal text”, Variable Arithmetic Operations ( ) ^ * / % + - Relational Operators Logical Operators = AND <> < > >= <= OR NOT 4 -35
Pseudocode Language (Ch 4) Previous pseudocode Create a module Module. Name content End Selection If-Then-Else Structure If condition Then do something Else do something else End If Call a sub-module Call Module. Name Case Structure Select Case of something Case: X do something Case: Y do something Default: do something End Case 4 -36
- Loaded language examples in advertising
- Types of repetition
- Homology
- What is the poem kamikaze about
- Prelude stealing the boat
- Prelude to programming 6th edition
- Prelude to programming 6th edition
- Prelude 7 erp
- Gérard baglin
- The prelude extract
- Skating william wordsworth
- Eprelude
- E-prelude.com
- Excerpt from the prelude
- Compare the prelude and storm on the island
- Sequential circuits prelude
- Maurane sur un prélude de bach analyse
- Prelude hybrid ids
- Prelude to programming 6th edition
- Prelude to reformation
- Chapter 67 neo romantic evocations
- Specsavers prelude
- Optician industry
- The prelude annotated
- Eprelude
- E-prelude
- Pseudocode for loop
- Pascal looping
- Looping writing
- Bentuk umum statement for
- List the different categories of qbasic looping statements
- Nested for loop alternative
- Perulangan bersarang java
- Disadvantages of looping in education
- Exit controlled loop flowchart
- Dangling in network diagram
- Automatic counter loop