Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.

Similar presentations


Presentation on theme: "Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and."— Presentation transcript:

1 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and Elizabeth Drake Chapter 4: Repetition Structures: Looping

2 4-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 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.

3 4-3 Flowchart for a Simple Loop

4 4-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 4-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 Num Until Num = 0 Write “Done”

6 4-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 4-7 Examples (review from Chapter 3) Given: A = 23, B = 16 Then: A > B is true A < B is false A >= B is true A <= B is false A <> B is true A = B is false

8 4-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 4-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 4-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 4-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 4-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 4-13 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’.

14 4-14 The NOT Operator AND and O R 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 4-15 Truth Tables for OR, AND, and NOT Operators XYX OR YX AND YNOT X true false truefalsetruefalse true falsetrue false true

16 4-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 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

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

18 4-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

19 4-19 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 Set Count = 1 While Count <= N Write Count, Count ^ 2 Set Count = Count + 1 End While If the user enters 4: N = 4 Count Output 1 1 1 2 2 4 3 3 9 4 4 16

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

21 4-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 11 1 22 4 33 9 44 16 55 25 NOutput 1 3 5 … 17 17 19 19

22 4-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 4-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 4-24 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 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.

25 4-25 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 How many beans will be displayed? Set beans = 4 Set Count = 0 While Count < beans Write “bean” Set Count = Count + 1 End While

26 4-26 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 How many beans will be displayed? Set beans = 4 Set Count = 5 While Count < beans Write “bean” Set Count = Count - 1 End While

27 4-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 4-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 4-29 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

30 4-30 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 MaxValue Until Int(MaxValue) = MaxValue For Count = 1 Step 1 To MaxValue Write Count End For

31 4-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 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

32 4-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 4-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 More code here End While Until

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

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

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


Download ppt "Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and."

Similar presentations


Ads by Google