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! David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey.

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; 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 while statement Does statement while condition true
does statement 0 or more times statement condition true false while (condition) statement;

5 If you print out count as well as the asterisk, what do you get?
Examples (1) Print 5 asterisk characters Use 5 println statements! Use a single println statement! Use a while loop… * * * * * done count = 0; while ( count < 5 ) { System.out.println( “*”); count = count + 1; } System.out.println( “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 count too. If you print out count as well as the asterisk, what do you get?

6 Examples (2) Read & sum 5 values By analogy…
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.

7 Immediately initialize to 0 (1) before loop
Examples (3) Extract design patterns/templates Counting loop… Count, sum or product in loop… count = 0; while ( count < numberOfRepetitions ) { // process to repeat count = count + 1; } Such design patterns are extremely important. They encode good engineering practice. Remembering/using them in the appropriate places saves time and effort. Immediately initialize to 0 (1) before loop

8 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!

9 Proving loops terminate (1)
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”);

10 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”); 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 year or so back. Is it correct? Lots of pages!! Halting problem, a limit to computation! Proof that cannot always write program to determine whether given algorithm will halt or not. (ref. Halting Problem – Alan Turing.)

11 Reading 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 Sentinel value non-data value marks end of list Consider advantages/disadvantages of each Sentinel is value that guards/marks the end of the set. non-data value (not always possible to find)

12 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 Try developing this from beginning. Look at wrong options too! Extract another design pattern read value while value is not the sentinel process the value read next value

13 Examples (sentinel input)
Find average of set of exam scores. Count number of positive & negative values entered by user. Use zero to stop input. Allow user to enter a set of positive values terminated by a zero. When the user enters zero, print a msg to indicate whether any value exceeded a threshold or not. Read a set of positive values & report whether they were in ascending order or not. Read a set of positive values & report their maximum. Extend to minimum.

14 Java for statements Same as while loop!
Use as short-hand counting style loop statement condition true false update init for ( init; condition; update) statement; Notes: variable i is often defined in the for loop; will not be visible outside! Variables only visible inside block defined in. i++ is shorthand notation for i = i + 1; Example: for ( i = 0; i < 5; i = i + 1) System.out.println( “*”);

15 Java do-while statements
Repeat 1 or more times do statement; while (condition); statement condition true false Example: i = 0; do { System.out.println( “*”); i++; } while ( i < 5);

16 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 Read value btw 5 & 10 inclusive. do { System.out.print( “Enter positive value: ”); value = scan.nextInt(); } while ( value <= 0); // assert: value > 0

17 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” ABC Trading Co 1 – sales 2 – stock 3 – admin Select (0 to exit): _ Write algorithm for display menu & perform selection tasks Translate into Java. 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

18

19 More practice? Process characters in String Process digits in an int
Use stringVariable.charAt( int pos) & stringVariable.length() Process digits in an int Use / & % to split it up Compute PI & e using sequence Compute square root (Newton Raphson) Print table of projectile motion


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

Similar presentations


Ads by Google