Java Coding 3 David Davenport Computer Eng. Dept.,

Slides:



Advertisements
Similar presentations
Java Coding 8 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Object-Oriented Design Example - The.
Advertisements

Java Coding OOP David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Towards Event-driven programming &
Everyday Algorithms David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. lightning introduction to.
Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Computer Science 1620 Loops.
Java Coding 2 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Decisions, decisions…!
Java Coding 3 David Davenport Computer Eng. Dept.,
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Review: OOP & Arrays David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. …from CS101.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
Java Coding David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey.
Java Coding 3 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Over & over again!
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
Java Programming: From the Ground Up
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
CIS 234: LOOPS Adapted from materials by Dr. Donald Bell, 2000 (updated April 2007)
Computational Algorithms David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. lightning introduction.
30/10/ Iteration Loops Do While (condition is true) … Loop.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
CS101 Computer Programming I Chapter 4 Extra Examples.
CMP-MX21: Lecture 5 Repetitions Steve Hordley. Overview 1. Repetition using the do-while construct 2. Repetition using the while construct 3. Repetition.
Java Coding OOP_3 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Some important Java interfaces +
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Java Coding 5 – Part 2 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. To object or not…
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Feedback  Lab2, Hw1  Groups  Group Project Requirements.
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Java Coding – part 2 David Davenport Computer Eng. Dept.,
Chapter 5: Control Structures II
Repetition (While-Loop) version]
Java Coding 3 – part2 David Davenport Computer Eng. Dept.,
Chapter 5: Control Structures II
Chapter 5: Control Structures II
Repetition-Counter control Loop
Lecture 07 More Repetition Richard Gesick.
Lecture 4B More Repetition Richard Gesick
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Control Structures - Repetition
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Chapter 4 Control structures and Loops
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Looping and Repetition
Conditions and Ifs BIS1523 – Lecture 8.
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Outline Altering flow of control Boolean expressions
CS1100 Computational Engineering
Java Programming Loops
Do While (condition is true) … Loop
Java Coding 6-extra David Davenport Computer Eng. Dept.,
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Chapter 6: Repetition Statements
Java Coding 6 – part2 David Davenport Computer Eng. Dept.,
CSC115 Introduction to Computer Programming
Flowcharts and Pseudo Code
Java Programming Loops
Java Coding 4 (part2) David Davenport Computer Eng. Dept.,
Repetition Statements
Java Coding 6_part3 David Davenport Computer Eng. Dept.,
Building Java Programs
Building Java Programs
Java Coding 6 David Davenport Computer Eng. Dept.,
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Java Coding 6 David Davenport Computer Eng. Dept.,
Switch Case Structures
Presentation transcript:

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. email: david@bilkent.edu.tr 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

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

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

the most general form of repetition While…

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

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

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.

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?

Examples (2) Read & sum 5 values by analogy! 5 3 7 4 1 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.

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

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

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!

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

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, 1937. 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.)

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 3 5 7 4 1 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)

Sentinel-controlled input…? Read & sum values until sentinel 5 3 7 4 1 -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!

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

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

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

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 4444444

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!