Motivations Chapter 5: Loops And Iteration

2y ago
11 Views
3 Downloads
2.63 MB
9 Pages
Last View : 19d ago
Last Download : 3m ago
Upload by : Eli Jorgenson
Transcription

9/13/18MotivationsChapter 5: Loops and IterationSuppose that you need to print a string (e.g.,"Welcome to Java!") a hundred times. It would betedious to have to write the following statement ahundred times:CS1: Java ProgrammingColorado State UniversitySystem.out.println("Welcome to Java!");So, how do you solve this problem?Original slides by Daniel LiangModified slides by Chris WilcoxLiang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.1Introducing while LoopsOpening Problemint count 0;while (count 100) {System.out.println("Welcome to Java");count ;Java!");Java!");Java!");Java!");Java!"); System.out.println("Welcome to Java!");System.out.println("Welcome to Java!");System.out.println("Welcome to Java!");Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.3Objectives§ To write programs for executing statements repeatedly using a while loop(§5.2).§ To follow the loop design strategy to develop loops (§§5.2.1–5.2.3).§ To control a loop with a sentinel value (§5.2.4).§ To obtain large input from a file using input redirection rather than typingfrom the keyboard (§5.2.5).§ To write loops using do-while statements (§5.3).§ To write loops using for statements (§5.4).§ To discover the similarities and differences of three types of loop statements(§5.5).§ To write nested loops (§5.6).§ To learn the techniques for minimizing numerical errors (§5.7).§ To learn loops from a variety of examples (GCD, FutureTuition,Dec2Hex) (§5.8).§ To implement program control with break and continue (§5.9).§ To write a program that displays prime numbers (§5.11).Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.54while Loop Flow Chartwhile (loop-continuation-condition) {// loop-body;Statement(s);}int count 0;while (count 100) {System.out.println("Welcome to Java!");count ;}Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.61

9/13/18animationanimationTrace while Loopint count 0;Initialize countint count 0;while (count 2) {System.out.println("Welcome to Java!");count ;count ;}}Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.7animationTrace while Loop, cont.int count 0;Print Welcome to Java8Trace while Loop, cont.int count 0;while (count 2) {Increase count by 1count is 1 nowwhile (count 2) {System.out.println("Welcome to Java!");System.out.println("Welcome to Java!");count ;count ;}}Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.animation(count 2) is truewhile (count 2) {System.out.println("Welcome to Java!");animationTrace while Loop, cont.animationTrace while Loop, cont.int count 0;Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.9(count 2) is still true since countis 1while (count 2) {10Trace while Loop, cont.int count 0;Print Welcome to Javawhile (count 2) {System.out.println("Welcome to Java!");System.out.println("Welcome to Java!");count ;count ;}}Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.11Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.122

9/13/18animationanimationTrace while Loop, cont.Increase count by 1count is 2 nowint count 0;Trace while Loop, cont.(count 2) is false since count is 2nowint count 0;while (count 2) {while (count 2) {System.out.println("Welcome to Java!");System.out.println("Welcome to Java!");count ;count ;}}Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.animation13Trace while Loop14Problem: Repeat Addition Until CorrectThe loop exits. Execute the nextstatement after the loop.int count 0;Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.while (count 2) {System.out.println("Welcome to Java!");count ;}Recall that Listing 3.1 AdditionQuiz.java gives aprogram that prompts the user to enter an answerfor a question on addition of two single digits.Using a loop, you can now rewrite the program tolet the user enter a new answer until it is correct.IMPORTANT NOTE: If you cannot run the buttons,see tAdditionQuizLiang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.15RunLiang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.16Problem: Guessing NumbersProblem: An Advanced Math Learning ToolWrite a program that randomly generates aninteger between 0 and 100, inclusive. The programprompts the user to enter a number continuouslyuntil the number matches the randomly generatednumber. For each user input, the program tells theuser whether the input is too low or too high, sothe user can choose the next input intelligently.Here is a sample run:The Math subtraction learning tool programgenerates just one question for each run. You canuse a loop to generate questions repeatedly. Thisexample gives a program that generates fivequestions and reports the number of the correctanswers after a student answers all five , Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.SubtractionQuizLoop17RunLiang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.183

9/13/18Ending a Loop with a Sentinel ValueOften the number of times a loop is executed is notpredetermined. You may use an input value tosignify the end of the loop. Such a value is knownas a sentinel value.Write a program that reads and calculates the sumof an unspecified number of integers. The input 0signifies the end of the input.SentinelValueLiang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.RunCautionDon’t use floating-point values for equality checking in aloop control. Since floating-point values areapproximations for some values, using them could resultin imprecise counter values and inaccurate results.Consider the following code for computing 1 0.9 0.8 . 0.1:double item 1; double sum 0;while (item ! 0) { // No guarantee item will be 0sum item;item - 0.1;}System.out.println(sum);Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.1920for Loopsdo-while Loopfor (initial-action; loopcontinuation-condition; actionafter-each-iteration) {// loop body;Statement(s);}int i;for (i 0; i 100; i ) {System.out.println("Welcome to Java!");}do {// Loop body;Statement(s);} while (loop-continuation-condition);Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.animationanimationTrace for Loopint i;for (i 0; i 2; i ) {System.out.println("Welcome to Java!");}Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.21Declare iLiang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.Trace for Loop, cont.int i;for (i 0; i 2; i ) {System.out.println("Welcome to Java!");}2322Execute initializeri is now 0Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.244

9/13/18animationint i;for (i 0; i 2; i ) {System.out.println( "Welcome to Java!");}(i 2) is truesince i is 0Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.animationanimationint i;for (i 0; i 2; i ) {System.out.println("Welcome to Java!");}Print Welcome to JavaLiang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.28Trace for Loop, cont.int i;for (i 0; i 2; i ) {System.out.println("Welcome to Java!");}29(i 2) is still truesince i is 1Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.animation26Trace for Loop, cont.int i;for (i 0; i 2; i ) {System.out.println("Welcome to Java!");}27Trace for Loop, cont.Print Welcome to JavaLiang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.25Execute adjustment statementi now is 1Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.Trace for Loop, cont.int i;for (i 0; i 2; i ) {System.out.println("Welcome to Java!");}Trace for Loop, cont.int i;for (i 0; i 2; i ) {System.out.println("Welcome to Java!");}animationanimationTrace for Loop, cont.Execute adjustment statementi now is 2Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.305

9/13/18animationanimationTrace for Loop, cont.int i;for (i 0; i 2; i ) {System.out.println("Welcome to Java!");}(i 2) is falsesince i is 2Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.Trace for Loop, cont.int i;for (i 0; i 2; i ) {System.out.println("Welcome to Java!");}31Exit the loop. Execute the nextstatement after the loopLiang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.32NoteNoteThe initial-action in a for loop can be a list of zero or morecomma-separated expressions. The action-after-eachiteration in a for loop can be a list of zero or more commaseparated statements. Therefore, the following two forloops are correct. They are rarely used in practice,however.If the loop-continuation-condition in a for loop is omitted,it is implicitly true. Thus the statement given below in (a),which is an infinite loop, is correct. Nevertheless, it isbetter to use the equivalent loop in (b) to avoid confusion:for (int i 1; i 100; System.out.println(i ));for ( ; ; ) {// Do something}Equivalentwhile (true) {// Do something}(a)for (int i 0, j 0; (i j 10); i , j ) {(b)// Do something}Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.33Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.34Caution, cont.CautionSimilarly, the following loop is also wrong:Adding a semicolon at the end of the for clause beforethe loop body is a common mistake, as shown below:LogicErrorIn the case of the do loop, the following semicolon isneeded to end the loop.for (int i 0; i 10; i );{System.out.println("i is " i);}Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.int i 0;Logic Errorwhile (i 10);{System.out.println("i is " i);i ;}int i 0;do {System.out.println("i is " i);i ;Correct} while (i 10);35Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.366

9/13/18Which Loop to Use?The three forms of loop statements, while, do-while, and for, areexpressively equivalent; that is, you can write a loop in any of thesethree forms. For example, a while loop in (a) in the following figurecan always be converted into the following for loop in (b):while (loop-continuation-condition) {// Loop body}Equivalentfor ( ; loop-continuation-condition; ) {// Loop body}(a)(b)A for loop in (a) in the following figure can generally be converted into thefollowing while loop in (b) except in certain special cases (see Review Question3.19 for one of them):for -after-each-iteration) {// Loop body;}EquivalentRecommendationsUse the one that is most intuitive and comfortable foryou. In general, a for loop may be used if the number ofrepetitions is known, as, for example, when you need toprint a message 100 times. A while loop may be used ifthe number of repetitions is not known, as in the case ofreading the numbers until the input is 0. A do-while loopcan be used to replace a while loop if the loop body has tobe executed before testing the continuation condition.initial-action;while (loop-continuation-condition) {// Loop body;action-after-each-iteration;}(a)(b)Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.3738Minimizing Numerical ErrorsNested LoopsProblem: Write a program that uses nested forloops to print a multiplication table.MultiplicationTableLiang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.Numeric errors involving floating-pointnumbers are inevitable. This section discusseshow to minimize such errors through anexample.Here is an example that sums a series thatstarts with 0.01 and ends with 1.0. Thenumbers in the series will increment by 0.01,as follows: 0.01 0.02 0.03 and so on.RunTestSumLiang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.39Problem:Finding the Greatest Common DivisorProblem: Write a program that prompts the user to enter two positiveintegers and finds their greatest common divisor.RunLiang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.40Problem: Predicting the Future TuitionProblem: Suppose that the tuition for a university is 10,000 this yearand tuition increases 7% every year. In how many years will thetuition be doubled?Solution: Suppose you enter two integers 4 and 2, their greatestcommon divisor is 2. Suppose you enter two integers 16 and 24, theirgreatest common divisor is 8. So, how do you find the greatest commondivisor? Let the two input integers be n1 and n2. You know number 1 isa common divisor, but it may not be the greatest commons divisor. Soyou can check whether k (for k 2, 3, 4, and so on) is a commondivisor for n1 and n2, until k is greater than n1 or n2.FutureTuitionGreatestCommonDivisorLiang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.RunRun41Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.427

9/13/18Case Study: Converting Decimals toProblem: Predicating the Future Tuitiondouble tuition 10000; int year 0 // Year 0tuition tuition * 1.07; year ;// Year 1tuition tuition * 1.07; year ;// Year 2tuition tuition * 1.07; year ;// Year 3.HexadecimalsHexadecimals are often used in computer systems programming (seeAppendix F for an introduction to number systems). How do youconvert a decimal number to a hexadecimal number? To convert adecimal number d to a hexadecimal number is to find the hexadecimaldigits hn, hn-1, hn-2, . , h2, h1, and h0 such thatd hn 16n hn - 1 16n -1 hn - 2 16n - 2 . h 2 162 h1 161 h 0 160These hexadecimal digits can be found by successively dividing d by16 until the quotient is 0. The remainders are h0, h1, h2, . , hn-2, hn-1,and hn.Dec2HexLiang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.43Companion Website44Using break and continueProblem: Monte Carlo SimulationExamples for using the break and continuekeywords:The Monte Carlo simulation refers to a technique that uses randomnumbers and probability to solve problems. This method has a widerange of applications in computational mathematics, physics,chemistry, and finance. This section gives an example of using theMonto Carlo simulation for estimating p. circleArea / squareArea p / 4.yRunTestBreak.javaTestBreakRun1-11p can be approximated as 4 *numberOfHits / numberOfTrialsxMonteCarloSimulation-1Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved. TestContinueRunpublic class TestContinue {public static void main(String[] args) {int sum 0;int number 0;while (number 20) {number ;sum number;if (sum 100)break;}while (number 20) {number ;if (number 10 number 11)continue;sum number;}System.out.println("The number is " number);System.out.println("The sum is " sum);}Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.46continuepublic class TestBreak {public static void main(String[] args) {int sum 0;int number 0;}RunLiang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights intln("The sum is " sum);Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.488

9/13/18Problem: Checking PalindromeGuessing Number Problem RevisitedHere is a program for guessing a number. You canrewrite it using a break statement.A string is a palindrome if it reads the same forward and backward.The words “mom,” “dad,” and “noon,” for instance, are allpalindromes.The problem is to write a program that prompts the user to enter astring and reports whether the string is a palindrome. One solution isto check whether the first character in the string is the same as the lastcharacter. If so, check whether the second character is the same as thesecond-to-last character. This process continues until a mismatch isfound or all the characters in the string are checked, except for themiddle character if the string has an odd number of characters.RunGuessNumberUsingBreaklowString sahighbcdefgnhgfedcbaPalindromeLiang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.49Problem: Displaying Prime NumbersProblem: Write a program that displays the first 50 prime numbers infive lines, each of which contains 10 numbers. An integer greater than1 is prime if its only positive divisor is 1 or itself. For example, 2, 3,5, and 7 are prime numbers, but 4, 6, 8, and 9 are not.CompanionWebsiteRun50Debugging Loops in IDE ToolsSupplements II.C, II.E, and II.G.Solution: The problem can be broken into the following tasks: For number 2, 3, 4, 5, 6, ., test whether the number is prime. Determine whether a given number is prime. Count the prime numbers. Print each prime number, and print 10 numbers per line.PrimeNumberLiang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.Run51Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. Allrights reserved.529

§To write loops using do-whilestatements (§5.3). §To write loops using forstatements (§5.4). §To discover the similarities and differences of three types of loop statements (§5.5). §To write nested loops ( §5.6). §To learn the techniques for minimizing numerical errors ( §5.7). §To

Related Documents:

Part One: Heir of Ash Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14 Chapter 15 Chapter 16 Chapter 17 Chapter 18 Chapter 19 Chapter 20 Chapter 21 Chapter 22 Chapter 23 Chapter 24 Chapter 25 Chapter 26 Chapter 27 Chapter 28 Chapter 29 Chapter 30 .

TO KILL A MOCKINGBIRD. Contents Dedication Epigraph Part One Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Part Two Chapter 12 Chapter 13 Chapter 14 Chapter 15 Chapter 16 Chapter 17 Chapter 18. Chapter 19 Chapter 20 Chapter 21 Chapter 22 Chapter 23 Chapter 24 Chapter 25 Chapter 26

DEDICATION PART ONE Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 PART TWO Chapter 12 Chapter 13 Chapter 14 Chapter 15 Chapter 16 Chapter 17 Chapter 18 Chapter 19 Chapter 20 Chapter 21 Chapter 22 Chapter 23 .

Public Art Loops These loops may be enjoyed by biking, walking, or running. Solo or in a group. Virtually all the public art can be enjoyed by riding on the pathways! For even more exercise, ride two or more loops. There are more than 50 parks on these loops -Take a few minutes to enjoy our fabulous parks! For a map of all .

SME volunteer motivations is a key task when developing successful strategies not only for recruiting and training, but also for satisfying and retaining SME volunteers [5]. 1.1. Motivations of Volunteering at Sport Events Volunteering motivations have been widely studied, and various multi-dimensional models have been proposed [7].

volunteer motivations represent multi-dimensional aspects of individuals. Clary and Snyder (1991) assessed volunteering motivations by adopting the functional approach to volunteering motivations which change or form individuals' attitudes and further lead them to engage in certain activities [28].

About the husband’s secret. Dedication Epigraph Pandora Monday Chapter One Chapter Two Chapter Three Chapter Four Chapter Five Tuesday Chapter Six Chapter Seven. Chapter Eight Chapter Nine Chapter Ten Chapter Eleven Chapter Twelve Chapter Thirteen Chapter Fourteen Chapter Fifteen Chapter Sixteen Chapter Seventeen Chapter Eighteen

12 dimana manajer menggeser laba tahun berjalan dengan kemungkinan laba di masa mendatang. Sedangkan menurut Kustono (2009), perataan laba dapat didefinisi sebagai suatu cara yang dipakai manajemen untuk mengurangi variabilitas laba di antara deretan jumlah laba yang timbul karena adanya perbedaan antara jumlah laba yang seharusnya dilaporkan dengan laba yang diharapkan (laba normal). 2.2.2 .