Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Coding 3 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Over & over again!

Similar presentations


Presentation on theme: "Java Coding 3 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Over & over again!"— Presentation transcript:

1 Java Coding 3 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. email: david@bilkent.edu.tr Over & over again!

2 IMPORTANT… Students… 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 email saying where and when it is/was used. I would also appreciate any suggestions you may have for improving it. thank you, David. David

3 Repetition Java repetition statements do statement; while (condition); while (condition) statement; where statement is any Java statement condition is a boolean expression for ( init; condition; update) statement;

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

5 Examples (1) Print 5 asterisk characters Use 5 println statements! Use a single println statement! Use a while loop… starsPrinted is 0 while starsPrinted < 5 do print a star add 1 to starsPrinted print “done” * * * * * done

6 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”

7 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”); If you print out count as well as the star, what do you get? * * * * * done

8 Read & sum 5 values by analogy! read value add value to sum report sum Examples (2) 5 3 7 4 1 sum is 20 sum is 0 sum is 0 while __________ do read value add value to sum report sum sum is 0 count is 0 while count < 5 do read value add value to sum add 1 to count report sum

9 Examples (2) Read & sum 5 values 5 3 7 4 1 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); Named constant or ask for & get value from user

10 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 Immediately initialize to 0 (1) before loop

11 Generic form of while 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! initialise any variables in condition while (test condition variable) do statement & update condition variables;

12 Proving loops terminate (1) Do these print “done”? i = 1; while ( i != 50 ) { System.out.println( i); i = i + 2; } System.out.println( “done”); count = 0; while ( count < 5 ) { System.out.println( “*”); count = count - 1; } System.out.println( “done”);

13 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”); Proof that cannot write program to determine whether every algorithm will halt or not. (ref. Halting Problem – Alan Turing.)

14 Reading a set of data Three approaches How many? 5 3 5 7 4 1 sum is 20 More? Y 3 More? Y 5 More? Y 7 More? Y 4 More? Y 1 More? N sum is 20 3 5 7 4 1 sum is 20 Sentinel value non-data value marks end of list Must say “no more”

15 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 read value while value is not the sentinel process the value read next value Extract another design pattern

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

17 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: 10 Enter values (0 to stop): 3 12 7 14 6 0 Limit WAS exceeded. Enter limit: 8 Enter values (0 to stop): 5 2 7 4 0 Limit NOT exceeded.

18 Questions (1) 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 * *** ***** ******* 1 222 33333 4444444

19 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 …)

20 FOR & DO-WHILE …other forms of repetition in Java

21 Java for statements Same as while loop! Use as short-hand counting style loop for ( init; condition; update) statement; statement condition true false update init Example: for ( i = 0; i < 5; i = i + 1) System.out.println( “*”);

22 Questions (1) 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 * *** ***** ******* 1 222 33333 4444444 1 212 32123 4321234 ******* ***** *** *

23 Example Ask the user for their name, print it out one character per line, then print “done”. Enter your name: David D a v i d done. print 1 st char in name “ 2 nd “ “ “ “ 3 rd “ “ “ “ : “ “ “ “ last “ “ “ print charAt 0 in name “ “ 1 “ “ “ “ 2 “ “ “ “ : “ “ “ “ last “ “ for index = 0 to ___________ print charAt index in name for (index = 0; index < name.length(); index++) System.out.println( name.charAt( index) );

24 Using Java methods… To use, need to know Method name Inputs & their types Output type answer = f( x, y, z ); input parameters output result type Method name // in String class… public String substring( int beginIndex, int endIndex) // usage… shortString = longString.substring( 1, 3); // in Math class public static double sin( double d) double d = Math.sin( 0.5); Use ClassName.method(…) for “static” methods varName.method(…) for non-static methods

25 Example Ask the user for their name, print it out one character per line, then print “done”. Enter your name: David D a v i d done. Enter your name: David d i v a D done. now do it in reverse! Finally… From either sequence of characters, construct a String, reverseName

26 Question Given an integer, print its digits in reverse sequence, one per line. Enter integer: 372 2 7 3 done. Enter an integer: 372 Reversed is: 273 Now reconstruct the reverse integer Note: you are not allowed to use the power function!

27 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);

28 Examples (do-while) Data validation e.g. Read positive value from user do { System.out.print( “Enter positive value: ”); value = scan.nextInt(); } while ( value 0 do ask for “a positive value” and get value while value is not positive

29 Examples (do-while) Menus - set of options for user to select from ABC Trading Co. ------------------ 1 – sales 2 – stock 3 – admin Select (0 to exit) : _ 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

30

31 More practice? Process characters in String 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 Print calendar for given month


Download ppt "Java Coding 3 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Over & over again!"

Similar presentations


Ads by Google