Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Coding 3 David Davenport Computer Eng. Dept.,

Similar presentations


Presentation on theme: "Java Coding 3 David Davenport Computer Eng. Dept.,"— Presentation transcript:

1 Java Coding 3 David Davenport Computer Eng. Dept.,
Over & over again: using while Sentinel-controlled input David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Last revised: 20/10/2017 ~ separated while from other forms of repetition Previously: 8/11/2016, 26/10/2016 ~ minor revisions 20/10/2016 ~ Added new animated slide for sentinel-controlled input, etc. 22/10/2012

2 IMPORTANT… Students… Instructors…
This presentation is designed to be used in class as part of a guided discovery sequence. It is not self-explanatory! Please use it only for revision purposes after having taken the class. Simply flicking through the slides will teach you nothing. You must be actively thinking, doing and questioning to learn! Instructors… You are free to use this presentation in your classes and to make any modifications to it that you wish. All I ask is an saying where and when it is/was used. I would also appreciate any suggestions you may have for improving it. thank you, David.

3 Repetition Java repetition statements while (condition) statement; do
for ( init; condition; update) statement; Java has three forms of repetition statement: while, for & do-while They can all essentially equivalent… we will concentrate on while & treat others as special cases Statement to be repeated, input, output, assignment, decision, repetition! Condition exactly as for if statements where statement is any Java statement condition is a boolean expression

4 the most general form of repetition
While…

5 The while statement Does statement while condition true
does statement 0 or more times statement condition true false while (condition) statement; loop

6 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” Use algorithm to begin with. Start with printing a single “*”, add loop and observe need to count number printed so far. Show can print out starsPrinted too… what does it give? Do in Java… note need for compound statement (curly brackets!)

7 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” Use algorithm to begin with. Start with printing a single “*”, add loop and observe need to count number printed so far. Show can print out starsLeftToPrint too… what would it give? Demo in Java.

8 If you print out count as well as the star, what do you get?
Examples (1) Print 5 asterisk characters * * * * * done starsPrinted = 0; while (starsPrinted < 5 ) { System.out.println( “*”); starsPrinted = starsPrinted + 1; } System.out.println( “done”); Replaced variable with more generic one! ( could even replace count with i ) Use algorithm to begin with. Start with printing a single “*”, add loop and observe need to count number printed so far. Show can print out count too. Replace print “*” with print count… -- does it print 0? 5? What is the value of count after the loop? (what can we assert is true about the value of count after loop?) -- logic? (to exit loop its condition must be false, i.e. “count < 5” must be false, therefore “count >= 5” ) Note lots of solutions… e.g. 1 & <= 5, or 1 & < 6 or -5 & < 0, etc. also count down, 5 downto 0 etc. Prefer soln that directly maps problem values into code, - e.g. the number 5 in the problem to the 5 in the code would be much better than soln with loop from 1 to 6. Will remember one as design pattern… 0 , < 5 (since this most useful in Java!) count = 0; while ( count < 5 ) { System.out.println( “*”); count = count + 1; } System.out.println( “done”); If you print out count as well as the star, what do you get?

9 Examples (2) Read & sum 5 values
by analogy! sum is 20 sum is 0 count is 0 while count < 5 do read value add value to sum add 1 to count report sum read value add value to sum report sum sum is 0 while __________ do read value add value to sum report sum sum is 0 Again begin from algorithm; what do you need to repeat (read value & add to sum), then put in loop & figure out condition Note: should be using named constant to 5 here! Modify to ask user number of values to sum up.

10 Named constant or ask for & get value from user
Examples (2) Read & sum 5 values Named constant or ask for & get value from user sum is 20 sum = 0; count = 0; while ( count < 5 ) { value = scan.nextInt(); sum = sum + value; count = count + 1; } System.out.println( “sum is ” + sum); Again begin from algorithm; what do you need to repeat (read value & add to sum), then put in loop & figure out condition Note: should be using named constant to 5 here! Modify to ask user number of values to sum up.

11 Immediately initialize to 0 (1) before loop
Examples (3) Extract design patterns/templates Counting loop… Count, sum or product in loop… count is 0 while count < numberOfRepetitions process to repeat add 1 to count Such design patterns are extremely important. They encode good engineering practice. Remembering/using them in the appropriate places saves time, effort & mistakes! Note: This is only one possible solution… but is most useful in Java! Immediately initialize to 0 (1) before loop

12 Generic form of while What happens if you fail to… In general…
initialise any variables in condition while (test condition variable) do statement & update condition variables; What happens if you fail to… Initialise loop variables Unpredictable behaviour 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!

13 Proving loops terminate (1)
Do these print “done”? count = 0; while ( count < 5 ) { System.out.println( “*”); count = count - 1; } System.out.println( “done”); Actually try/demo these… - results may be surprising! Also… Numeric overflow +ve/-ve Caution when checking for exact equality esp. for real values (due to inherent error) Safer to check for range, i.e. while (i < 50) or band if absolutely necessary, i.e while ( Math.abs(d – desired) < epsilon) i = 1; while ( i != 50 ) { System.out.println( i); i = i + 2; } System.out.println( “done”);

14 Proving loops terminate (2)
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”); Collatz conjecture Lothar Collatz, Still open problem? Trace for i = 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1, done. At least until quite recently no proof that the example halted, but it always did for every no. tried! Cem Tozer from METU published “proof” a few year ago. Is it correct? Lots of pages!! Halting problem, a limit to computation! Alan Turing, On computable numbers, with an application to the Entscheidungsproblem, 1937 Proof that cannot write program to determine whether any given algorithm will halt or not. (ref. Halting Problem – Alan Turing.)

15 Reading a set of data Three approaches How many? 5 3 5 7 4 1 sum is 20
More? Y 3 5 More? Y 7 More? Y 4 More? Y 1 More? N sum is 20 sum is 20 Must say “no more” Sentinel value non-data value marks end of list -1 Consider advantages/disadvantages of each First is ok, but not really user-friendly (easy to mis-count!) The middle one is ok, but in simple cases adds lots of typing overhead. Its fine for entering lots of data (eg. name & address) and is often applied to re-run/repeat some existing code/program e.g. to play a game again (may not want to ask to play first time though, so do-while may be better solution here?) The last one is more user-friendly data entry… (very common task!) Want to simply enter data, then somehow say “no more” or “stop” But if reading int values such a string would crash program Could read strings instead, but then need to convert into number for maths. Note: could also use scan.hasNextInt() to test first!! Sentinel is value that guards/marks the end of the set. same type as actual data non-data value (not always possible to find)

16 Sentinel-controlled input…?
Read & sum values until sentinel -1 sum is 20 sum is 0 read value while value != -1 do add value to sum read value report sum sum is 0 value is -27 while value != -1 do read value add value to sum report sum sum is 0 while value != -1 do read value add value to sum report sum sum is 0 read value while value != -1 do read value add value to sum report sum sum is 0 while __________ do read value add value to sum report sum read value add value to sum report sum sum is 0 Again begin from algorithm; what do you need to repeat (read value & add to sum), then report sum then put in loop remember to init sum! Oops… need to init value too… ?to any value? No, anything not the sentinel! Trace… Oops… wrong answer! Why? … Added sentinel into sum! Fix? Subtract sentinel from sum after loop? don’t add if sentinel? Alternate way to init value? … Read value from user Trace… still wrong (misses first value)… fix! Ok, finally this one looks good!

17 Sentinel-controlled input
Sum set of values terminated by -1 sum = 0 read value while value is not -1 do add value to sum read next value print sum Must process every value (inc. first) NOT process sentinel work for empty set Try developing this from beginning. Look at wrong options too! For example: sum = 0 value = -27  omit to begin with… note problem of init while while value is not the sentinel do read next value add value to sum print sum Trace & see adds sentinel to sum ? Fix ? - many patches possible e.g. print sum +1; print sum – sentinel; if value is not sentinel then add value to sum; even, sum = -sentinel; Can always “fix” a program, but try to rethink, find more elegant solution! Ensure solution: (a) does not process the sentinel, (b) processes all other values—including the first, & (c) processes the empty set correctly. Extract another design pattern read value while value is not the sentinel process the value read next value

18 Examples (sentinel input)
Find the average of set of exam scores. Allow user to enter any number of scores; stop and report the average when a negative score is entered. Write a program that allows the user to enter a set of values. When the user enters zero it should stop and report the number of positive and the number of negative values entered. 5, 3, -7, 2, -4, 0  3 positive & 2 negative values entered. 0  0 positive & 0 negative values entered. 9, 2, 8, 0  3 positive & 0 negative values entered. -4, -8, -3, -5, 0  0 positive & 4 negative values entered. Average problem was solved at beginning of semester & is a simple extension to the previous sum of positive values problem. (add noOfPapers & possibly noOfPapers == 0 check!) PosNegCount problem is straightforward, but the main idea is top-down design using the pattern. So: find the noOfPos & noOfNeg values in a set of values read from the user & terminated by 0. Report noOfPos & noOfNeg values entered. Then recognise 1 as a case of sentinel-controlled input, so rewrite as: Read value While value is not sentinel Process value Fill in sentinel (=0) & processs “if value is positive then add 1 to noOfPos else add 1 to noOfNeg” Immediately, recall other design pattern, viz. doing a count/sum/product in a loop, init before loop!” & so add “noOfPos = 0” and “noOfNeg = 0” before loop. Extract data/memory requirements: noOfPos, noOfNeg, value – int variables SENTINEL – int constant = 0 Now write & demo in Java Explicitly demo auto layout features of IDE? Note test data sets given in question… (normally need to think of them yourself)!

19 Examples (sentinel input)
Allow user to enter a limit value, followed by a set of positive values terminated by a zero. After the user enters zero, print a message to say whether any of the values exceeded the given limit or not. Enter limit: 8 Enter values (0 to stop): Limit NOT exceeded. Enter limit: 10 Enter values (0 to stop): 6 0 Limit WAS exceeded. Top-level algorithm: Ask for & get limitValue Read a set of positive values terminated by zero ( & using limitValue find if limitExceeded ) if limitExceeded then print “Limit WAS exceeded” else print “Limit NOT exceeded” Omit parts in italics to begin with… ask what is needed? (note alternative of simply counting noOverLimit & testing if noOverLimit > 0) Extract data/memory requirements limitValue – int variable limitExceeded – boolean variable Write in Java… (outline solution for step 2, but leave as homework to do in Java). Need additional test data, especially empty data set? Note: Can be an idea to do this in three forms: Counting number over limit Replace count with simply setting it to 1 inside loop Realise can replace this int with boolean. (describe in terms of man with flag…)

20 Questions (1) * *** ***** ******* 1 222 33333 4444444
Read a set of positive values & report their maximum after the user enters a negative value. Extend to minimum. Allow the user to enter a set of positive values & report whether they were in ascending order or not. Write a program that asks the user to enter an integer number N, then prints a triangle with N lines of stars or numbers. For example, if N is 4 Try to apply top-down design to these problems Then implement & test in Java. * *** ***** ******* 1 222 33333

21 Questions (2) Compute PI using the series expansion by evaluating: (a) a fixed number of terms (b) enough terms until a specified accuracy is achieved, e.g. until the value changes < 0.001 For intervals of 0.1 seconds, compute and print the height of a mass falling from a given initial height, until it hits the ground. PI = 4 * ( 1 - 1/3 + 1/5 - 1/7 + 1/9 …) Emphasise care needed when dealing with real values Specify range of values for loop condition rather than single exact value!


Download ppt "Java Coding 3 David Davenport Computer Eng. Dept.,"

Similar presentations


Ads by Google