Java Coding 3 Over & over again!
Repetition Java repetition statements while (condition) statement; do statement; while (condition); where for ( init; condition; update) statement; statement is any Java statement condition is a boolean expression
The while statement Does statement while condition true does statement 0 or more times while (condition) statement; true condition loop statement false
Syntax 5.1 while Statement Copyright 2014 by John Wiley & Sons. All rights reserved. 4
Examples (1) Print 5 asterisk characters Use 5 println statements! Use a single println statement! Use a while loop * * * * * done starsprinted is 0 while starsprinted < 5 do print a star add 1 to starsprinted print done Remember: curly brackets!
Examples (1) Print 5 stars (asterisk characters) Use 5 println statements! Use a single println statement! Use repetition (a loop ) * * * * * done starslefttoprint is 5 while there are starslefttoprint do print a star subtract 1 from starslefttoprint print done
Examples (1) Print 5 asterisk characters Use 5 println statements! Use a single println statement! Use a while loop count = 0; while ( count < 5 ) { System.out.println( * ); count = count + 1; } System.out.println( done ); * * * * * done If you print out count as well as the star, what do you get?
Stars import java.util.scanner; public class Play1 { public static void main( String[] args) { Scanner scan = new Scanner( System.in); System.out.println( "Start of Play1\n"); // CONSTANTS final int STARS_REQUIRED = 5; // VARIABLES int int starsprinted; starslefttoprint; double d;
Stars // ********************************** // First solution // ********************************** starsprinted = 0; while ( starsprinted < STARS_REQUIRED ) { System.out.println( "* " + starsprinted); starsprinted = starsprinted + 1; } // assert: starsprinted >= 5 System.out.println( "\ndone " + starsprinted); } // ********************************** System.out.println( "\nend of Play1\n" ); } // end of class Play1
Stars // ********************************** // Alternative solution // ********************************** starslefttoprint = STARS_REQUIRED; while ( starslefttoprint > 0) { System.out.println( "* " + starslefttoprint); starslefttoprint = starslefttoprint - 1; } } // assert: starslefttoprint <= 0 System.out.println( "\ndone " + starslefttoprint); } // end of class Play1
Stars d = 0.0; while ( d!= 1.0) // change to (d <= 1.0) to see what happens! { System.out.println( d); d = d + 0.1; } System.out.println( "done " + d); System.out.println(); } } // end of class Play1
Examples (2) Read & sum 5 values sum is 0 count is 0 while count < 5 do read read value value add add value value to sum to sum add 1 to count 5 3 7 4 1 sum is 20 report sum
Examples (2) Read & sum 5 values Named constant or ask for & get value from user sum = 0; count = 0; while ( count < 5 ) { value = scan.nextint(); sum = sum + value; count = count + 1; } System.out.println( sum is + sum); 5 3 7 4 1 sum is 20 Modify to ask user number of values to sum up.
Generic form of while initialise any variables in condition while (test condition variable) do statement & update condition variables; What happens if you fail to Initialize loop variables Unpredictable behavior Update loop variables Infinite loop! (in console app s use Ctrl-C to exit) In general condition must be falsifiable by applying update to initial values need proof!
Common Error: Infinite Loops Do these print done? count = 0; while ( count < 5 ) { System.out.println( * ); count = count - 1; } System.out.println( done ); i = 1; while ( i!= 50 ) { System.out.println( i); i = i + 2; } System.out.println( done );
Common Error: Infinite Loops What about this one? i = scan.nextint(); while ( i!= 1 ) { if ( i % 2 == 0) i = i / 2; else i = 3 * i + 1; } System.out.println( done ); Proof that cannot write program to determine whether every algorithm will halt or not. (ref. Halting Problem Alan Turing.)
Common Error: Off-by-One Errors Off-by-one error: a loop executes one too few, or one too many, times. Example: int years = 0; while (balance < targetbalance) { years++; balance = balance * (1 + RATE / 100); } System.out.println("The investment doubled after " + year + " years."); Should years start at 0 or 1? Should the test be < or <=? Copyright 2014 by John Wiley & Sons. All rights reserved. 17
Avoiding Off-by-One Error Look at a scenario with simple values: initial balance: $100 interest rate: 50% after year 1, the balance is $150 after year 2 it is $225, or over $200 so the investment doubled after 2 years the loop executed two times, incrementing years each time Therefore: years must start at 0, not at 1. interest rate: 100% after one year: balance is 2 * initialbalance loop should stop Therefore: must use < not <= Think, don't compile and try at random Copyright 2014 by John Wiley & Sons. All rights reserved. 18
Reading a set of data First approach How many? 5 3 5 7 4 1 sum is 20 It is ok, but not really userfriendly (easy to mis-count!)
Reading a set of data Second approach More? Y 3 More? Y 5 More? Y 7 More? Y 4 More? Y 1 More? N sum is 20 Ok, but in simple cases adds lots of typing overhead. Fine for entering lots of data (eg. name & address) Often applied to re-run/repeat some existing code/program (to play a game again)
Reading a set of data 3 5 7 4 1-1 Third approach sum is 20 Must say no more Sentinel value non-data value marks end of list More user-friendly for low volume data entry Want to simply enter data, then somehow say no more or stop If reading int values such a string would crash the program Could read strings instead, but then need to convert into number for maths Sentinel is value that guards/marks the end of the set same type as actual data non-data value (not always possible to find)
Sentinel-controlled input Sum set of values terminated by -1 sum = 0 read value while value is not the sentinel do add value to sum read next value print sum Extract another design pattern read value while value is not the sentinel process the value read next value
Sentinel-controlled input Look at wrong options sum = 0 while value is not the sentinel do read next value add value to sum print sum adds sentinel to sum Ensure solution: (a) does not process the sentinel (b) processes all other values including the first (c) processes the empty set correctly
Examples (sentinel input) Next week
More While Examples
The while Loop Investment problem You put $10,000 into a bank account that earns 5 percent interest per year. How many years does it take for the account balance to be double the original investment? The algorithm Start with a year value of 0, a column for the interest, and a balance of $10,000. Repeat the following steps while the balance is less than $20,000. Add 1 to the year value. Compute the interest as balance x 0.05 (i.e., 5 percent interest). Add the interest to the balance. Report the final year value as the answer. Copyright 2014 by John Wiley & Sons. All rights reserved. 26
The while Loop The code: while (balance < targetbalance) { year++; double interest = balance * RATE / 100; balance = balance + interest; } Copyright 2014 by John Wiley & Sons. All rights reserved. 27
The while Loop Figure 1 Flowchart of a while Loop Copyright 2014 by John Wiley & Sons. All rights reserved. 28
while Loop Examples Copyright 2014 by John Wiley & Sons. All rights reserved. 29
Problem Solving: Hand-Tracing A simulation of code execution in which you step through instructions and track the values of the variables. What value is displayed? int n = 1729; int sum = 0; while (n > 0) { int digit = n % 10; sum = sum + digit; n = n / 10; } System.out.println(sum); Copyright 2014 by John Wiley & Sons. All rights reserved. 30
Problem Solving: Hand-Tracing - Step by Step Step 1 Step 2 Copyright 2014 by John Wiley & Sons. All rights reserved. 31
Problem Solving: Hand-Tracing - Step by Step Step 3 Copyright 2014 by John Wiley & Sons. All rights reserved. 32
Problem Solving: Hand-Tracing - Step by Step Step 4 Copyright 2014 by John Wiley & Sons. All rights reserved. 33
Problem Solving: Hand-Tracing - Step by Step Step 5 Copyright 2014 by John Wiley & Sons. All rights reserved. 34
Problem Solving: Hand-Tracing - Step by Step Step 6 Copyright 2014 by John Wiley & Sons. All rights reserved. 35
Problem Solving: Hand-Tracing - Step by Step Step 7 Copyright 2014 by John Wiley & Sons. All rights reserved. 36
Problem Solving: Hand-Tracing - Step by Step Step 8 Copyright 2014 by John Wiley & Sons. All rights reserved. 37
Problem Solving: Hand-Tracing - Step by Step Step 9 Step 10 The sum, which is 19, is printed Copyright 2014 by John Wiley & Sons. All rights reserved. 38
Self Check 5.6 Hand-trace the following code, showing the value of n and the output. int n = 5; while (n >= 0) { n--; System.out.print(n); } Answer: n output 5 4 4 3 3 2 2 1 1 0 0-1 -1 Copyright 2014 by John Wiley & Sons. All rights reserved. 39
Self Check 5.8 Hand-trace the following code, assuming that a is 2 and n is 4. Then explain what the code does for arbitrary values of a and n. int r = 1; int i = 1; while (i <= n) { r = r * a; i++; } Answer: a n r i 2 4 1 1 2 2 4 3 8 4 16 5 The code computes a n. Copyright 2014 by John Wiley & Sons. All rights reserved. 40
Self Check 5.9 Trace the following code. What error do you observe? int n = 1; while (n!= 50) { System.out.println(n); n = n + 10; } Answer: n output 1 1 11 11 21 21 31 31 41 41 51 51 61 61... This is an infinite loop. n is never equal to 50. Copyright 2014 by John Wiley & Sons. All rights reserved. 41
Self Check 5.10 The following pseudo-code is intended to count the number of digits in the number n: count = 1 temp = n while (temp > 10) Increment count Divide temp by 10.0 Trace the pseudocode for n = 123 and n = 100. What error do you find? Continued Copyright 2014 by John Wiley & Sons. All rights reserved. 42
Self Check 5.10 Answer: count temp 1 123 2 12.3 3 1.23 This yields the correct answer. The number 123 has 3 digits. count temp 1 100 2 10.0 This yields the wrong answer. The number 100 also has 3 digits. The loop condition should have been while (temp >= 10). Copyright 2014 by John Wiley & Sons. All rights reserved. 43
Application: Processing Sentinel Values To compute the average of a set of salaries use -1 to indicate termination Inside the loop Read the input process it if the input is not -1 Stay in the loop while the sentinel value is not -1. Initialize the input to something other than -1. Copyright 2014 by John Wiley & Sons. All rights reserved. 44
section_5/sentineldemo.java 1 import java.util.scanner; 2 3 /** 4 This program prints the average of salary values that are terminated with a sentinel. 5 */ 6 public class SentinelDemo 7 { 8 public static void main(string[] args) 9 { 10 double sum = 0; 11 int count = 0; 12 double salary = 0; 13 System.out.print("Enter salaries, -1 to finish: "); 14 Scanner in = new Scanner(System.in); 15 16 // Process data until the sentinel is entered 17 Continu ed Copyright 2014 by John Wiley & Sons. All rights reserved. 45
section_5/sentineldemo.java 16 // Process data until the sentinel is entered 17 18 while (salary!= -1) 19 { 20 salary = in.nextdouble(); 21 if (salary!= -1) 22 { 23 sum = sum + salary; 24 count++; 25 } 26 } 27 28 // Compute and print the average 29 30 if (count > 0) 31 { 32 double average = sum / count; 33 System.out.println("Average salary: " + average); 34 } 35 else 36 { 37 System.out.println("No data"); 38 } 39 } 40 } Continu ed Copyright 2014 by John Wiley & Sons. All rights reserved. 46
section_5/sentineldemo.java Program Run Enter salaries, -1 to finish: 10 10 40-1 Average salary: 20 Copyright 2014 by John Wiley & Sons. All rights reserved. 47
Application: Processing Sentinel Values Using a Boolean variable to control a loop. Set the variable before entering the loop Set it to the opposite to leave the loop. System.out.print("Enter salaries, -1 to finish: "); boolean done = false; while (!done) { value = in.nextdouble(); if (value == -1) { done = true; } else { Process value } } Copyright 2014 by John Wiley & Sons. All rights reserved. 48
Application: Processing Sentinel Values When any number can be an acceptable input Use a sentinel value that is not a number (such as the letter Q) in.hasnextdouble() returns false if the input is not a floating-point number Use this loop System.out.print("Enter values, Q to quit: "); while (in.hasnextdouble()) { value = in.nextdouble(); Process value. } Copyright 2014 by John Wiley & Sons. All rights reserved. 49
Self Check 5.21 What does the SentinelDemo.java program print when the user immediately types -1 when prompted for a value? Answer: No data Copyright 2014 by John Wiley & Sons. All rights reserved. 50
Self Check 5.22 Why does the SentinelDemo.java program have two checks of the form salary!= -1? Answer: The first check ends the loop after the sentinel has been read. The second check ensures that the sentinel is not processed as an input value. Copyright 2014 by John Wiley & Sons. All rights reserved. 51
Self Check 5.23 What would happen if the declaration of the salary variable in SentinelDemo.java was changed to double salary = -1; Answer: The while loop would never be entered. The user would never be prompted for input. Because count stays 0, the program would then print "No data". Copyright 2014 by John Wiley & Sons. All rights reserved. 52
Self Check 5.24 In the last example of this section, we prompt the user "Enter values, Q to quit: " What happens when the user enters a different letter? Answer: The nextdouble method also returns false. A more accurate prompt would have been: "Enter values, a key other than a digit to quit: " But that might be more confusing to the program user who would need to ponder which key to choose. Copyright 2014 by John Wiley & Sons. All rights reserved. 53
For & Do-while other forms of repetition in Java
Java for statements Same as while loop! Use as short-hand counting style loop for ( init; condition; update) statement; false init condition true statement Example: for ( i = 0; i < 5; i = i + 1) System.out.println( * ); update
Java for statements for ( init; condition; update) statement; Has advantage of explicitly reminding you about init & update Easy to forget when writing a while loop Variable i is often defined inside the for statement for ( int i = 0; i < 5; i++) System;out.println( * ); System;out.println( i = + i); // will not compile! i will not be visible outside (after the loop) Variables only visible inside block they are defined in. important! i++ is shorthand notation for i = i + 1;
The for Loop To execute a sequence of statements a given number of times: Could use a while loop controlled by a counter int counter = 1; // Initialize the counter while (counter <= 10) // Check the counter { System.out.println(counter); counter++; // Update the counter } Use a special type of loop called for loop for (int counter = 1; counter <= 10; counter++) { System.out.println(counter); } Use a for loop when a variable runs from a starting value to an ending value with a constant increment or decrement. Copyright 2014 by John Wiley & Sons. All rights reserved. 57
Syntax 5.2 for Statement Copyright 2014 by John Wiley & Sons. All rights reserved. 58
The for Loop The initialization is executed once, before the loop is entered. The condition is checked before each iteration. The update is executed after each iteration. Copyright 2014 by John Wiley & Sons. All rights reserved. 59
The for Loop A for loop can count down instead of up: for (int counter = 10; counter >= 0; counter--)... The increment or decrement need not be in steps of 1: for (int counter = 0; counter <= 10; counter = counter + 2)... Copyright 2014 by John Wiley & Sons. All rights reserved. 60
The for Loop If the counter variable is defined in the loop header, It does not exist after the loop for (int counter = 1; counter <= 10; counter++) {... } // counter no longer declared here If you declare the counter variable before the loop, You can continue to use it after the loop int counter; for (counter = 1; counter <= 10; counter++) {... } // counter still declared here Copyright 2014 by John Wiley & Sons. All rights reserved. 61
Java do-while statements Repeat 1 or more times Example: do statement; while (condition); statement i = 0; do { System.out.println( * ); i++; } while ( i < 5); condition false true { on same line as while (); can help avoid confusion! Also, ; is required here (in do-while statement), but not in while statement
Examples (do-while) Data validation e.g. Read positive value from user do ask for a positive value and get value while value is not positive do { System.out.print( Enter positive value: ); value = scan.nextint(); } while ( value <= 0); // assert: value > 0
Examples (do-while) Menus - set of options for user to select from do display menu get selection from user perform selection while selection is not exit print goodbye if selection is SALES then // do sales things else if selection is STOCK then // do stock things else if selection is ADMIN then // do admin things else if selection is not EXIT then print invalid selection msg ABC Trading Co. ------------------ 1 sales 2 stock 3 admin Select (0 to exit): _
Self Check 5.16 Suppose that we want to check for inputs that are at least 0 and at most 100. Modify the do loop for this check. int value; do { System.out.print("Enter an integer < 100: "); value = in.nextint(); } while (value >= 100); Answer: do } { System.out.print( "Enter a value between 0 and 100: "); value = in.nextint(); while (value < 0 value > 100); Copyright 2014 by John Wiley & Sons. All rights reserved. 65
Self Check 5.17 Rewrite the input check do loop using a while loop. What is the disadvantage of your solution? int value; do { System.out.print("Enter an integer < 100: "); value =in.nextint(); } while (value >= 100); Answer: int value = 100; while (value >= 100) { System.out.print("Enter a value < 100: "); value = in.nextint(); } Here, the variable value had to be initialized with an artificial value to ensure that the loop is entered at least once. Copyright 2014 by John Wiley & Sons. All rights reserved. 66
Self Check 5.18 Suppose Java didn't have a do loop. Could you rewrite any do loop as a while loop? Answer: Yes. The do loop do { Body } while (condition); is equivalent to this while loop: boolean first = true; while (first condition) { body; first = false; } Copyright 2014 by John Wiley & Sons. All rights reserved. 67