Presentation is loading. Please wait.

Presentation is loading. Please wait.

Intro to Programming & Algorithm Design

Similar presentations


Presentation on theme: "Intro to Programming & Algorithm Design"— Presentation transcript:

1 Intro to Programming & Algorithm Design
4/23/2017 Intro to Programming & Algorithm Design Loops NG Assg Labs This presentation can be viewed on line in a file named: ch05.IntrotoProg.ppt Copyright 2003 by Janson Industries

2 4/23/2017 Objectives Explain Advantages of loops Different types of loops Common loop mistakes Show how to implement the various loop types in Java

3 4/23/2017 Why Loops? If a set of instructions needs to be repeated many times, best to use a loop rather than repeating the instructions Less coding Fewer mistakes For example, to keep executing with an unknown number of data records, you can't do it without a loop

4 Why Loops? Example Here's pseudocode for a program to double a number
4/23/2017 Here's pseudocode for a program to double a number To double another number we have to rerun the program For example... Module main Declare Integer numToDouble, result Display “Enter number to double and press Enter” Input numToDouble result = numToDouble * 2 Display “2 X ”, numToDouble, “ = ”, result End Module

5 To double another number, have to issue the java command again
We want program to just ask for another number...

6 4/23/2017 Why Loops? Example With a loop, we could have the instructions run again And again, and again, and.... Module main Declare Integer numToDouble, result BeginLoop Display “Enter number to double and press Enter” Input numToDouble result = numToDouble * 2 Display “2 X ”, numToDouble, “ = ”, result EndLoop End Module

7 4/23/2017 Why Loops? This is why loops have to check a control variable to see if they should process the statements again How and when the check is done is the difference between the different types of loops Condition-controlled Count-controlled

8 4/23/2017 Why Loops? Condition-controlled loops use a true/false condition to determine how many times to loop While executes when condition true Do While executes when condition true Do Until executes when condition false Count-controlled loops execute a specific number of times For

9 4/23/2017 Why Loops? Condition-controlled loops also differentiated by when the condition is checked While is a pre-test loop Do While is a post-test loop Do Until is a post-test loop

10 Loops While loop – pre-test
Checks the condition first and only executes if condition true : : : While hair = “dirty” Lather Rinse Display "Is hair dirty or clean" Input hair End While

11 Loops 4/23/2017 While Condition check done first If check true, executes statements Lather and rinse will not be executed if condition is false Input… Display… Is hair = “dirty” True Lather Rinse False False

12 4/23/2017 Loops In While, Do While, and Do Until loops, the programmer explicitly manipulates the control variable(s) In java, while loop syntax is Keyword while Condition (in parenthesis) Statements to execute (in braces) while (condition) { statements to execute }

13 Simple pre-test loop example
Notice loop runs 4 times even though check is "counter < 4" Control variable (counter) defined outside of loop and manipulated inside loop

14 Loops Do While – post-test Do Until – post-test
Checks condition at end and executes if condition true Do Until – post-test Checks condition at end and executes if condition false Loops Do : : While hair = “dirty” Do : : Until hair = “clean”

15 4/23/2017 Loops Do While condition test done at end of loop Lather and rinse will always be executed at least once whether the condition is true or not but only continues if true Lather Rinse Is hair = “dirty” True False

16 4/23/2017 Loops Do Until Condition test done at end of loop Lather and rinse will always be executed at least once whether the condition is true or not but only continues if false Lather Rinse Is hair = “clean” False True

17 Do While Loops In java, do while loop syntax is Keyword do
4/23/2017 Do While Loops In java, do while loop syntax is Keyword do Statements to execute (in braces) Keyword while Condition (in parenthesis) do { statements to execute } while(condition)

18 Answer: if numberOfTimesToLoop = 0
Simple post-test loop example - Notice loop runs 4 times (just like pretest) What condition(s) would result in different output for the different loop types? Answer: if numberOfTimesToLoop = 0

19 Do Until Loops In java, there is no Do Until
4/23/2017 Do Until Loops In java, there is no Do Until Closest you can come to a Do Until is use a Do While and negate the condition do { statements to execute } while(!condition)

20 For Loop A little complicated
4/23/2017 For Loop A little complicated Does a lot of stuff very compactly Most for statements allow the programmer to specify A loop control variable An initial value for the variable An evaluation condition A Boolean expression with the loop control variable A variable update value

21 For Loop Pseudo code example: ctr = 1 to 3 step 1 Declare Integer ctr
4/23/2017 Pseudo code example: Declare Integer ctr For ctr = 1 to 3 step 1 statements to be repeated End For Defines the loop control variable ctr ctr = 1 to 3 Initializes ctr to 1 and defines the max value for ctr step 1 defines the increment value as 1

22 For Loop If you don’t specify a step value the default is 1
4/23/2017 For Loop If you don’t specify a step value the default is 1 Declare Integer ctr For ctr = 1 to 2 Lather Rinse End For

23 For Loop Executes a defined number of times In this case twice
4/23/2017 For Loop Executes a defined number of times In this case twice Also called a definite loop, counted loop, counter controlled loop for ctr =1 to 2 True Lather Rinse False False

24 Java For Loop The for keyword Then in parenthesis
4/23/2017 The for keyword Then in parenthesis Loop control variable definition (optional) and initialization Semicolon The loop condition evaluation The step increment definition Then in braces the statements to be repeated for (int ctr = 1; ctr < 3; ctr = ctr + 1) { statements to be repeated }

25 Java For Loop Example int ctr = 1 ctr < 3 ctr = ctr + 1
4/23/2017 Example for (int ctr = 1; ctr < 3; ctr = ctr + 1) { statements to be repeated } int ctr = 1 Creates the variable ctr Initializes ctr to 1 ctr < 3 Defines the condition to check ctr = ctr + 1 Defines the increment as 1

26 For Loop If the loop is going to execute a fixed number of times
4/23/2017 For Loop If the loop is going to execute a fixed number of times For loop easier than while or do while Instead of statements to Define the control variable Define the limit Increment the control variable And the do or do while keywords You use the for statement to do all those things

27 Notice how much less code is needed

28 For Loop To truly understand the For loop, you have to understand
4/23/2017 For Loop To truly understand the For loop, you have to understand The generally accepted interpretation of the pseudocode and/or flowchart text When all the "pieces" of the for statement are performed

29 4/23/2017 For Loop If the pseudocode had specified 0 to 99 (0 and 99 are inclusive) It means the statements should be executed 100 times Once when it was 0 Once when it was 1 Etc, etc, etc Once when it was 99

30 4/23/2017 For Loop To get the for loop to work the same way with java, could specify any of these int ctr = 0; ctr <100; ctr = ctr + 1 int ctr = 0; ctr <= 99; ctr = ctr + 1 int ctr = 1; ctr <101; ctr = ctr + 1 int ctr = 1; ctr <= 100; ctr = ctr + 1

31 For Loop Why? Because the for does "int ctr = 1" first and only once
4/23/2017 For Loop Why? Because the for does "int ctr = 1" first and only once Then repeatedly The condition is checked If condition is true Statements are executed Ctr is incremented by one When the condition is false The statement after the End For is executed

32 For Loop int ctr = 1 Is ctr < 3 Perform Statements ctr = ctr +1
4/23/2017 For Loop int ctr = 1 Is ctr < 3 Perform Statements ctr = ctr +1 True False

33 For Loop In the pseudocode 1 to 2 means
4/23/2017 In the pseudocode 1 to 2 means Do the statements while the control variable is equal to 1 or 2 This means The variable is initially set to 1 Condition is checked The statements are performed The variable is incremented to 2 The variable is incremented to 3 The statement after the End For is performed

34 Sentinel Values 4/23/2017 Sometimes you want a loop to execute until a user enters a value the means “stop the loop” Called a sentinel value While or Do While best for this Declare Integer userInput, result Input userInput While (userInput > 0) result = userInput * 2 Display result End While

35 Back To Our Original Problem
4/23/2017 Back To Our Original Problem Want to run doubling app until user indicates to stop In addition, we want to add non-logical (aka physical) requirements to design User interface Formatting

36 Back To Our Original Problem
4/23/2017 Back To Our Original Problem External Design (XD) Enter number you would like to double and press Enter. 4 2 x 4 = 8 -1 OK, you entered a value <= 0, ending execution

37 Final flow chart and pseudocode

38 4/23/2017 Notice design does not worry about peculiarities of the programming language

39 Create a Raptor FC and run to verify we have the correct logic
4/23/2017 Create a Raptor FC and run to verify we have the correct logic

40 Final java class looks like this
import java.io.IOException; import java.util.Scanner; public class DoubleWithWhile { public static void main(String[] args) { // Variable and object needed to read from command line Scanner keyboard = new Scanner(System.in); // Variables needed to hold input, intermediate values, and results int numToDouble = 0; int result = 0; // Prints out a blank line and instruction System.out.println(" "); System.out.print("Enter number would you like to double and press Enter. "); // Priming read numToDouble = keyboard.nextInt(); // Start of loop and check for sentinel value while (numToDouble > 0){ // Calculates and displays result result = numToDouble * 2; System.out.println("2 X " + numToDouble + " = " + result); 4/23/2017 Final java class looks like this

41 // Prints out a blank line and instruction System.out.println(" ");
4/23/2017 // Prints out a blank line and instruction System.out.println(" "); System.out.print("Enter number would you like to double and press Enter. "); // Reads next user input numToDouble = keyboard.nextInt(); // End of loop } // Quitting message System.out.print("OK, you entered a value <= 0, ending execution. "); // End of method // End of class

42 With a loop, problem solved

43 Loops Lots of reasons to use loops Accumulating Data validation
4/23/2017 Lots of reasons to use loops Accumulating A shopping cart of items Totals Data validation Declare Integer empAge Display "Enter employee age" Input empAge While (empAge > 95 OR empAge < 16) Display "Enter a valid age between 16 & 95" End While

44 Totaling in a Loop Module main Declare Real cost, totalCost
4/23/2017 Module main Declare Real cost, totalCost Display “Enter first item cost" Input cost While (cost > 0) totalCost = totalCost +cost Display “Enter next item cost or zero to end" End While Display “The total cost for all items is $“ , totalCost End Module

45 Can keep count of how many items are entered and display
4/23/2017 Module main Declare Real cost, totalCost Declare Integer counter = 0 Display “Enter first item cost" Input cost While (cost > 0) counter = counter + 1 totalCost = totalCost +cost Display “Enter next item cost or zero to end" End While Display “The total cost for the “ , counter , “ item(s) is $“ , totalCost End Module Can keep count of how many items are entered and display

46 Nested Loops Loops within loops
4/23/2017 Nested Loops Loops within loops Example, a report that reads and prints a file's contents and has the following format: Report header For each page A page header with page number For next 33 items Print line item A page footer with page number Report footer

47 Exercise XD Report will look like Report Header Page Header on Page #
4/23/2017 Report Header Exercise XD Report will look like Page Header on Page # ################################################## Page Footer on Page #

48 Exercise XD Can be a variable number of pages Report Footer
4/23/2017 Page Header on Page # ################################################## Page Footer on Page # Exercise XD Can be a variable number of pages Report Footer

49 4/23/2017 Nested Loops When a file is read, system returns a boolean value to indicate if there is anymore data Called an "end of file" indicator Indicator abbreviated as eof eof has a boolean value of true or false Can be used to control looping

50 Nested Loops Inner Loop Outer Loop Module main
4/23/2017 Nested Loops Module main Declare Integer pageCtr = 1, lineCtr = 0 Print Report Header and Skip to next page pageCtr = pageCtr + 1 Read record From file While (not eof) Print Page Header and pageCtr While (lineCtr < 33 AND not eof) Print item From record lineCtr = lineCtr + 1 End While lineCtr = 0 Print Page Footer and pageCtr Skip to next page Print Report Footer End Module Inner Loop Outer Loop

51 Exercise Design (SFC) an application that:
4/23/2017 Design (SFC) an application that: Gets customer account data from a file that has account number, customer name, and balance due For each customer: Print the account number and name Then for each month for the next 10 months Print the customer’s projected balance Assume: No finance or interest charge Customer makes no new purchases Customer pays off the balance with equal monthly payments of 10 percent of the original balance due

52 Algorithm 1. Read first record from the file 2. While not eof
4/23/2017 Algorithm 1. Read first record from the file 2. While not eof a. Display account number, customer name b. Then 10 times i. Subtract 10% from balance due ii. Display balance due c. Read next record from the file

53 Exercise XD Output will look like… Account Number: #######
4/23/2017 Output will look like… Account Number: ####### Customer: Xxxxx Xxxxxx Balance over next 10 months ######## Account Number: ########

54 Exercise What's input and what variables will you need to hold them?
4/23/2017 Exercise What's input and what variables will you need to hold them? acctNum for Account number custName for Customer name balanceDue for Balance due Based on calculation what variables will you need to hold intermediary and results? paymentAmt for 10 percent of the balance

55 Exercise So in flow chart, what's first? Then what?
Variable definition Then what? Priming read 4/23/2017

56 Exercise 4/23/2017 Then what? While that checks not eof

57 Exercise 4/23/2017 Then what? Print headers

58 Exercise 4/23/2017 Then what? Calc paymentAmt

59 Exercise Then what? For loop that runs 10 times to print balances
4/23/2017 Then what? For loop that runs 10 times to print balances For loop is nested within the while loop

60 Exercise 4/23/2017 Then what? Calc balanceDue and print it out

61 Exercise What happens when last balance printed? Blank line
4/23/2017 Exercise What happens when last balance printed? Blank line Read next record Check for end of file

62

63 Having an incorrect comparison
4/23/2017 Loop Gotchas Having an incorrect comparison

64 4/23/2017 Loop Gotchas Not initializing the control variable – in java, should always initialize

65 Not changing the control variable
4/23/2017 Loop Gotchas Not changing the control variable

66 Loop Gotchas The last example resulted in an infinite loop
4/23/2017 Loop Gotchas The last example resulted in an infinite loop The condition is never false Loop statements continually executed Can also happen because of a bad/trivial condition (always true) 1 == 1 End program execution by pressing and holding Ctrl key and then pressing C key (Crtl + C)

67 4/23/2017 Loop Exercise Assg 1 Program will calculate the number of bills needed for a dollar amount (until 0 entered) For instance, Program prompts user What is the dollar amount? User enters 58 Program displays 2 twenty(ies), 1 ten(s), 1 five(s) and 3 one(s) 20 is the largest denomination, no 2 dollar bills.

68 Loop Exercise Attack this in two parts Design everything else first
4/23/2017 Loop Exercise Attack this in two parts How to calculate the bills Everything else Design everything else first Answer 1

69 Bills Exercise Continued
4/23/2017 Bills Exercise Continued How to figure out the number of bills a little trickier First: you need variables to keep track of the number of bills for each denomination (bill counters) Couple of ways to do calc if value > than largest denomination Add one to that bill counter Subtract denomination from amount and check again else if value > second largest

70 Bills Exercise Continued
4/23/2017 Bills Exercise Continued So for example, if 58 (dollars) entered Check if dollars is bigger than 20 Yes Add one to 20 counter Subtract 20 from dollars, check again No if value > than 2nd largest denomination Add one to that bill counter Subtract denomination from dollars and check again else if …. Answer 2

71 Bills Exercise Continued
4/23/2017 Bills Exercise Continued Alternatively Divide the amount by the biggest denomination twentiesCtr = dollars/20 This assumes dolls is an integer so that the decimal remainder will be truncated Calc the remainder dollars = dollars – (twentiesCtr * 20) Divide the amount by the 2nd biggest denomination etc. Alt Answer

72 Bills Exercise Continued
4/23/2017 Bills Exercise Continued Let’s prove that it works by creating a Raptor FC Answer 3

73 4/23/2017 Non-graded Assg 1 Using nested loops, write a program to display the outer loops counter value as follows Don’t use math to generate numbers like 4,444 or 55,555 Send file, topic Ch05Assg1 Need a hint? 1 22 333 4444 55555

74 Points to Remember Loops are control structures that repeat actions
4/23/2017 Loops are control structures that repeat actions Makes computer programs more efficient Four general types While DoWhile DoUntil For Loops characterized as pretest or posttest

75 Points to Remember All require Can be nested Beware the infinite loop
4/23/2017 Points to Remember All require A loop control variable Which must be initialized and updated A condition that tests the control variable against a sentinel value Can be nested Beware the infinite loop

76 Assignments Non-Graded Graded Ch05Assg1 Chap 5 labs 4.1-4.4
4/23/2017 Assignments Non-Graded Ch05Assg1 Chap 5 labs Graded Chap 5 lab 4.5


Download ppt "Intro to Programming & Algorithm Design"

Similar presentations


Ads by Google