Chapter 5 Loops - PowerPoint PPT Presentation

chapter 5 loops n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Chapter 5 Loops PowerPoint Presentation
Download Presentation
Chapter 5 Loops

play fullscreen
1 / 98
Chapter 5 Loops
187 Views
Download Presentation
darrin
Download Presentation

Chapter 5 Loops

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. Chapter 5Loops Section 1 - While Loops Section 2 - For Loops Section 3 - printf Statements Section 4 - Loop Errors Section 5 - Nested Control Statements & Loop Errors Section 6 - Input & Output GUI Dialog Boxes Go Go Go Go Go Go

  2. Chapter 5 Section 1While Loops

  3. 5.1 What are Control Statements? We call …. if statements if-else statements while loops and for loops control statements because they control the order of execution in a Java program. 3

  4. 5.1 Definition of a While Loop In Java you can execute a segment of code over and over againwhile a boolean condition evaluates to true. When the boolean condition becomes false, the while loop will stop. There should be some code in the loop to make it stop, otherwise you will have an infinite loop (never-ending loop). A while loop looks like this: while (some boolean condition is true) { <execute these lines of code inside the loop body> } No code is executedif the boolean condition is initially false. The loop is skipped! 4

  5. 5.1 A Count Up while Loop Example A count-up while loop can be written to sum the integers from 1 to 3: int sum = 0; int cntr = 1; while (cntr <= 3) { sum += cntr; cntr++; } System.out.println(sum); Notice that here cntr, the loop control variable, is initialized to 1 before the loop and then it is incremented by 1 each time the body of the loop is executed. When cntr becomes 4, then the while loop condition will evaluate to false and the loop will immediately end.

  6. 5.1 Tracing a Count Up while Loop It is important to be able to trace the order of execution of a while loop to be able to fully understand how it works: int sum = 0; int cntr = 1; 1 while (cntr <= 3) 2 5 8 { sum += cntr; 3 6 9 cntr++; 4 7 10 } System.out.println(sum); 11 The blue numbers indicate the order the lines of code are executed in. Note: you are not required to used cntr in the mathematics or work of the loop as in the line sum += cntr; We just happen to be using it here as an easy way to help sum the numbers from 1 to 3. 6

  7. 5.1 Skeleton of a Count Up while Loop If you initially think about the problem of summing the numbers from 1 to 100, you should conclude that a loop is needed that will run 100 times. So the place to start is just to think about the basic parts of the loop that you need. Don’t worry about the mathematics or the work to be done inside the loop.Pull the necessary components together that will give you a loop that will run 100 times. Here is where you should start: int cntr = 1; while (cntr <= 100) { cntr++; } declare and initialize the loop control variable design a loop condition that will make the loop run the correct number of times increment the loop control variable at the bottom of the loop so the loop will eventually stop. 7

  8. 5.1 General Form of a while loop The while loop executes statements inside its body repeatedly for as long as its condition remains true. Every time the statements inside a while loop run, we say one iteration, one pass, or one repetition has occurred. while (condition) { // saves lines by putting { on same line of condition statement; statement; } No semicolon goes here! while (condition) No semicolon goes here! { // adds readability by putting curly brace { on separate line statement; statement; } No curly braces required for just one line of code in the loop.

  9. Consider the following code that sums the integers from 1 to 100: • intsum = 0; • intcntr = 1; • while(cntr <= 100) • { • sum += cntr; • cntr++; • } 5.1 Count-Controlled while Loops The sum is calculated as the number 5050. In a count-controlled loop, the loop control variable is incremented by one each time the loop runs. The variable cntr is the counter variable or loop control variable (lcv) and is declared and initialized before the while loop. This while loop repeats 100 times, because when the loop is encountered the value of cntr is 1 and it is incremented by 1 every time the body of the loop runs. The loop will run the final time when cntr is 100 and then when it becomes 101 inside the loop,then the loop condition evaluates to false and the body of the loop won’t execute anymore.

  10. 5.1 Count Down while Loops The following code uses a variation of the previous code to sum the integers from 100 down to 1. We call this a count down loop: • Countdown Loop code: • intsum = 0; • intcntr = 100; • while(cntr >= 1) • { • sum += cntr; • cntr--; • } • Original code: • intsum = 0; • intcntr = 1; • while(cntr <= 100) • { • sum += cntr; • cntr++; • } Note the code in the loop is exactly the same. Only the loop header and the initiaization value of the lcv have been changed.Compare the two codes to see the differences. 10

  11. 5.1 Varying while Loops Conditions • What if the boolean expression of the original code was changed from: • cntr <= 100 tocntr < 100 • intsum = 0, cntr = 1; • while(cntr < 100) • { • sum += cntr; • cntr++; • } • Then the loop runs only 99 times instead of 100and the value stored in sum is 4950 instead of 5050. 11

  12. You can make a loop control variable decrease in value as well as increase. It can decrease by 1 or by any other value you indicate. Here number is the loop control variable. • intnumber = 25; • while (number >= 10) • { • System.out.print("The square root of " + number);System.out.println(” is " + Math.sqrt(number)); • number -= 5; • } • Output in console window: • The square root of 25 is 5.0 • The square root of 20 is 4.47213595499958 • The square root of 15 is 3.872983346207417 • The square root of 10 is 3.1622776601683795 5.1 A Count-Down While Loop Example

  13. 5.1 A Count-Down While Loop Example • What if the boolean expression was changed from: • number >= 10 to number > 10 • int number = 25; • while (number > 10) • { • System.out.print("The square root of " + number);System.out.println(” is " + Math.sqrt(number)); • number -= 5; • } • The loop runs one less times and theOutput is: • The square root of 25 is 5.0 • The square root of 20 is 4.47213595499958 • The square root of 15 is 3.872983346207417 13

  14. 5.1 Calculating a Factorial Example • System.out.print("Enter a number greater than zero: "); • int number = reader.nextInt(); • int product = 1; • intcntr = 1; • while (cntr <= number) • { • product *= cntr; • cntr++; • } • System.out.print("The factorial of " + number); • System.out.println(" is " + product); The variable number can be referred to as the upper limit of the loop.

  15. 5.1 Task-Controlled While Loops A loop can execute until some task is accomplished. This code seeks to find the value of number once sum is greater than 1,000,000. int sum = 0; int number = 0; while ( sum <= 1000000) { number++; sum+= number; } System.out.print(“The first value of number for which”); System.out.println(“ sum is over 1,000,000 is: " + number); In this example, the loop control variable is sumbut it is not incremented by one or any other constant value each time the loop runs.

  16. 5.1 Interesting While Loop Example Code Example: Generate a random integer between -5 and 5 inclusive and store it in x. If x is positive find the square root of all values between 1 and x and print them out, otherwise do nothing. int x = (int) (Math.random() * 11 ) - 5; while (x > 0) { double root = Math.sqrt(x); System.out.println(“The square root of x is ” + root); x--; } Notice that if the value stored in x is between -5 and 0 inclusive, the loop will NOT run at all. Also notice that when x is positive, the loop will run and then x will be decremented by 1 and eventually x will become 0 and when it does then 0 > 0 evaluates to false and the loop stops. 16

  17. 5.1 User-Controlled While Loop Example The following code sums all the integers between two integers (inclusive) entered from the keyboard: Scanner reader = new Scanner (System.in); System.out.print(“Enter a starting value: ”); int startingValue = reader.nextInt(); System.out.print(“Enter an ending value greater than starting value: ”); int endingValue = reader.nextInt(); int sum = 0; int cntr = startingValue; while (cntr <= endingValue) { sum += cntr ; cntr++; } System.out.println(sum);

  18. initialize loop control variable // initialize • while (condition) // test the condition • { // execute the body of loop • perform calculations and • change variables involved in the condition • } 5.1 Order & Structure of a While Loop Initialize the loop control variable and other variables. Test the condition to try to enter the while loop. If successful entry, execute the body of the loop and then perform calculations and change the lcv and other variables. When the condition becomes false, the loop stops without executing the body.

  19. 5.1 Using a while (true) loop with Break Since true is a valid boolean value, a while(true) loop can be used. A while (true) loopcontinues to run until some condition makes it stop. This can be done by embedding a break statementinside an if statement inside the loop, so that when the if condition becomes true, the break statement will be executed and the loop will immediately stop. while (true) { System.out.print(“Enter a number or -1 to quit: ”); int x = reader.nextInt(); if (x ==-1) break; …. // lines of code that use x if it is not -1 } -1is called the sentinel because it makes the loop stop

  20. 5.1 A while (true) loop Example Here is a while-true loop example that … while(true) { System.out.print("Enter the person's age or -1 to quit: "); age = reader.nextInt(); if (age == -1) break; reader.nextLine(); // consume the new line character System.out.print("Enter the person's name: "); name = reader.nextLine(); if(age < 0 || age > 120) System.out.println("There is NO WAY you are alive " + name); else { System.out.println("The name of the person is: " + name); System.out.println("The age of the person is: " + age); } } // end of while(true) loop 20

  21. 5.1 Flow Chart for The while Statement Notice the return arrow after the last statement in the loop. It makes contact above the condition diamond. All the statements inside the loop go here.

  22. Chapter 5 Section 2For Loops

  23. 5.2 Definition of a For Loop In Java you can execute a segment of code over and over againusing a “for” loop. The key difference between a for and a while loop is you can place the declaration and initializationof the lcv (loop control variable), the test condition, and the lcvupdate statement all in the for loop header. A for loop looks like this: for (declare & initialize lcv; test condition; update lcv) { <lines of code inside the loop body> } Here no code is executed if the test condition is initially false. Note the curly braces { } that encompass all of the statements inside the for loop body. 23

  24. 5.2 A Simple for Loop Example int sum = 0; for (int cntr = 1; cntr <= 3; cntr++) { sum += cntr; } System.out.println(sum); Any while loop can be written as a for loop and vice-versa. Here is the code to sum the integers from 1 to 3. Compare it to the while loop version of the code. int sum = 0; int cntr = 1; while (cntr <= 3) { sum += cntr; cntr++; } System.out.println(sum); Observe the placement of the lcv (loop control variable) cntr in the two different loops. The next slide will show you the order of execution of the statements in the for loop. 24

  25. 5.2 The for Loop Order of Execution It is important to be able to trace the order of execution of a for loop. This will help you fully understand what is going on. The order of execution is indicated with the blue numbers. int sum = 0; for (int cntr = 1; cntr <= 3; cntr++) this is the for loop header { sum += cntr; } System.out.println(sum); Note: the loop control variable cntr is updated at the bottom of the loop, after the statements in the body have been executed. 1 3 6 9 12 5 8 11 2 Having cntr++ in the for loop headeris like having cntr++ here 4 7 10 13 25

  26. 5.2 A Second While & For Loop Comparison Compare the parts of the for loop and while loop versions of the code that sums all of the integers from 1 to 100: int sum = 0; int cntr = 1; while (cntr <= 100) { sum += cntr; cntr++; } System.out.println(sum); int sum = 0; for (intcntr = 1; cntr <= 100; cntr++) { sum += cntr; } System.out.println(sum); Any code you can write using a for loop can be written also using a while loop and vice versa. For loops provide an efficient way to write quickly a loop header that has all of the requirements of a loop and this can help you avoid loop errors. For loops are actually more readable, because you can see on one line if all of the necessary parts are present. 26

  27. 5.1 Skeleton of a Count Up for Loop If you initially think about the problem of summing the numbers from 1 to 100, you should conclude that a loop is needed that will run 100 times. So the place to start is just to think about the basic parts of the loop that you need. Don’t worry about the mathematics or the work to be done.Pull the necessary components together that will give you a loop that will run 100 times. Here is where you should start: for (int cntr = 1; cntr <= 100; cntr++) { } declare and initialize the loop control variable increment the loop control variable so the lcv will change and the loop will eventually stop. design a loop condition that will make the loop run the correct number of times 27

  28. 5.2 A User-Controlled for Loop We have already seen the following approach used with a while loop. Here is a similar version that uses a for loop. Scanner reader = new Scanner (System.in); System.out.print(“Enter a starting value: ”); intstartingValue = reader.nextInt(); System.out.print(“Enter an ending value greater than starting value: ”); intendingValue = reader.nextInt(); int sum = 0; for(int cntr = startingValue; cntr <= endingValue; cntr ++) { sum += cntr; } System.out.println("The sum is: " + sum);

  29. 5.2 A Count-Down for Loop A count-down for loop can be used similar to a while loop: // Display the square roots of 25, 20, 15, and 10 for ( int number = 25; number >= 10; number -= 5) { System.out.println(“The square root of ” + number + “ is ” + Math.sqrt(number)); } Notice as before with a while loop the test condition uses >=instead of <=. You could use > instead of < also.

  30. This code sums a list of numbers entered from the keyboard. You will find that i is used a lot as a loop control variable. This is by tradition. • double number; • double sum = 0; • System.out.print(“How long is the list? ”); • int count = reader.nextInt(); • for (int i = 1; i <= count; i++) • { • System.out.print(“Enter a positive number: ”); • number = reader.nextDouble(); • sum += number; • } 5.2 Count-Controlled Input with a for Loop Note: the letterihas long been used as a lcv. This is a tradition that has continued over the years with programmers.

  31. 5.2 Declaring a For Loops Control Variable It is possible to declare a for loop’s loop control variable (lcv) outside of the for loop header. However, possible program side-effects can occur with that variable if it is used after the loop in another segment of code. So if you declare the lcv outside the loop header for some reason, be careful and be sure and reinitialize if you use it in another loop. inti; // i declared before header for ( i = 1; i <= 10; i++) { System.out.println(i); } // not the preferred way to write it but ok if you need to use i outside the loop. // i declared inside header for (inti = 1; i <= 10; i++) { System.out.println(i); } // preferred way to write it if you don’t need to use i outside of the loop.

  32. 5.2 Declaring the LCV inside the Header In conclusion, generally, it is better to declare the loop control variable within the loop header for two reasons: • The variable i is only visible within the loop. This is a good thing. No side-effects. for (int i = 1; i <= 10; i++) System.out.println(i); i++; So if you try to write i++; outside the loop, Eclipse will complain that it doesn’t know i. This is because i was declared in the loop header and it is only available or known inside the loop … not outside.

  33. 5.2 Declaring the LCV inside the Header • If declared inside the loop header, the variable i can be reused later in other loops as the lcv without a side effect, even though it could be reset to one if it wasn’t declared inside the loop. for (int i = 1; i <= 10; i++) System.out.println(i); for (int i = 1; i <= 25; i++) System.out.println(i); One of the reasons for declaring the lcv inside the for loop header is that programmers traditionally like to use i as a loop control variable.In early programming languages, you wanted all of your code to be as short as possible, so if you needed different loop control variable names for different loops, then you used variables i, j, and k. Two different loops that both use i as the lcv.

  34. 5.2 Declaring the LCV Outside the Header However, you could still declare the lcv outside of the loop and use it in more than one loop, if you understand that i needs to be reset to one before it is used again. This is approach is used below in both for loop headers. int i; for (i = 1; i <= 10; i++) System.out.println(i); for (i = 1; i <= 25; i++) System.out.println(i);

  35. 5.2 for Loops or while Loops? Both for loops and while loops are calledentry-controlled loops, because the loop test condition is tested at top of the loop before the loop body is entered the first time and before each iteration. Choosing a for loop versus a while loop is often a matter of style, but a for loop has several advantages: • Can declare loop control variable in header • Initialization, condition, and update in one line of code • It is easy to see if you have everything you need to run the loop. It can be easy to overlook initializing all of the variables needed before executing a while loop. And it is easy to forget to update the loop control variable for a while loop. Many programmers forget to include cntr++.

  36. 5.2 Flow Chart for The for Loop Notice the return arrow after the last statement in the loop. It makes contact above the condition diamond. The flow chart for a for loop is the same as the flow chart for a while loop. 36

  37. Chapter 5 Section 3Formatting Console Outputwith printf statements

  38. 5.3 Introduction to printf statements print and println statements don’t allow us to easily format output to the screen or a file. However, a printf statement does. Just like the ln in println is an abbreviation for line. The f in printf is an abbreviation for format. Many times when we use loops to output a lot of data to the screen, we want it to be more readable. We can use printf statements to do this and to print items in columns. printf statements allow us to left justify output or right justify output. You can use both in the same statement to do things like start printing at the left margin but align output in columns. This makes the output more readable to the user of a program. Freezing =3 2 Boiling =2 1 2 Fiery =5 1 3 4 Nice =8 7 Super Hot =6 9 2 4 1 The words are left justified. The integers are right justified. 38

  39. 5.3 The Form of a printf Statement A printf statement always has the following form: System.out.printf ("format string", dataValue1, dataValue2, ....); Notice the format string and all data values are separated by commas NOT + signs. The format string is inside double quotes and there must be aformat specifierin it for each data value listed in the remainder of the statement. You can have any number of data values, but you must have one format specifier for every data value. The data values are NOT within double quotes unless they are a String value. Format specifiers always begin with the % symbol. 39

  40. 5.3 printf Statement Examples Here are three examples of printf statements. System.out.println has been replaced with System.out.printf. System.out.printf ("%7d”, fahrenheit); System.out.printf ("%10.4f”, percentage ); System.out.printf ("%20s”, phrase); Here fahrenheit is an int variable, percentage is a double variable, and phrase is a String variable. We’ll explain what is in the ( ) of a System.out.printf statement next. 40

  41. 5.3 The printf Format Specifiers There are three primary format specifiers that we will use: the letter d for decimal (base-10) int values as in %5d the letter f for decimalfloating point values as in %8.2f the letter s for string values as in %10s Also %n tells Java to display a new-line character, but youcan also use the escape sequence \n in its place. If a dash -follows the % symbol of a format specifier, then the data value will be left justified. If there is no dash then the data value is right justified. The - is called a format flag. You’ll see examples coming up. 41

  42. 5.3 The Format Specifier for int printf statements can right justifyinteger output. Consider this code: int fahrenheit = 212; System.out.printf("%7d”, fahrenheit); Once java sees the format specifier %7d then it retrieves the int data value stored in the variable fahrenheit (212). Java figures out that it needs 3 spaces to print 212 and then it calculates that it needs 7-3 spaces or 4 spaces before 212. So it skips 4 spaces from the left and then begins printing 212. It prints 212 in the 5th, 6th, and 7th spaces of the field width of 7 spaces. If we use an underscore character ‘_’ to represent a blank space, then the output would look like the following: _ _ _ _ 212 The printf statement right justifies the value stored in the variable fahrenheit in a field width of 7 spaces. 42

  43. 5.3 The Format Specifier for int We can also add other string information inside the format string that we want printed out prior to 212: int fahrenheit = 212; System.out.printf(“Temperature =%7d”, fahrenheit); Java will first print Temperature = and then when it sees the format specifier %7d then it retrieves the int data value stored in the variable fahrenheit (212). Again, Java figures out that it needs 3 spaces to print 212 and then skips 4 spaces from the left of the last thing printed and then begins printing 212. The output would look like the following with underscores again representing blank spaces: Temperature = _ _ _ _ 212 43

  44. 5.3 The Format Specifier for int We can also add other string information inside the format string that we want printed out after 212: int fahrenheit = 212; System.out.printf(“Temperature =%7d Fahrenheit”, fahrenheit); Java will first print Temperature = and then when it sees the format specifier %7d then it retrieves the int data value stored in the variable fahrenheit (212) and prints it right justified in the field width of 7. It then prints the word Fahrenheit after 212. The output would look like the following: Temperature = _ _ _ _ 212 Fahrenheit Make sure you realize that the %7d applies to fahrenheit the variable NOT Fahrenheit the word. 44

  45. 5.3 The Format Specifier for int You might be wondering … “Why would we want to use %7d?” The reason is a program may need to output temperature values of different sizes with all of the ones digits lined up, all of the tens digits lined up, all of the hundreds digits lined up, etc. In other words, we would want output to look like this with the numbers right justified: Temperature = _ _ _ _ _ 3 2 Fahrenheit Temperature = _ _ _ _ 2 1 2 Fahrenheit Temperature = _ _ _ 5 1 3 4 Fahrenheit Temperature = _ _ _ _ _ 8 7 Fahrenheit Temperature = _ _ 6 9 2 4 1 Fahrenheit 45

  46. 5.3 The Format Specifier for int You may be wondering what would Java do if the temperature was over 9,999,999, then Java would have to take an extra space to print all of the digits of the temperature and then the formatting would be off on that one line as seen below. Temperature = _ _ _ _ _ 3 2 Fahrenheit Temperature = _ _ _ _ 2 1 2 Fahrenheit Temperature = _ _ _ 5 1 3 4 Fahrenheit Temperature = _ _ _ _ _ 8 7 Fahrenheit Temperature = 3 7 5 6 9 2 4 1 Fahrenheit So it is important to choose a field width that is larger than the biggest number you expect to have in output. 46

  47. 5.3 Right Justified Output for int Here are random integers between 1 and 2000 that are right justified using a prinf statement with a field width of 4. Notice the ones digits, tens digits, hundreds digits, and thousands digits are lined up. 1102 295 1493 536 3 424 47 1983 1995 740 47

  48. 5.3 Left Justification for int You can use a printf statementto left justify output also.Consider the code: int fahrenheit = 212; System.out.printf ( "%-7d”, fahrenheit ); Once java sees the format specifier %-7d then it retrieves the data value stored in the variable fahrenheit (212). Java figures out that it needs 3 spaces to print 212 and then begins printing 212 at the left margin. It then advances 4 spaces to get ready to print the next thing. It prints 212 in the 1st, 2nd, and 3rd spaces of the field of 7 spaces. The output would look like the following: 2 1 2 _ _ _ _ The printf statement uses the - format flag to left justify the value stored in the variable fahrenheit in a field width of 10 spaces. 48

  49. 5.3 The Format Specifier for double printf statements can be set to round what is printed out.They don’t actually round what is in the variable, but they round what is seen on the screen.In this example, we will print right justified a floating point value in a field width of 10 with a precision of 4. double percentage = 99.3456789; System.out.printf (“ %10.4f ”, percentage ); Once java sees the format specifier %10.4f then it retrieves the data value stored in the variable percentage (99.3456789). Java figures out that it needs 4 spaces to print the part of the number to the right of the decimal point. It uses the number in the 5th decimal place (7) to round the number to .3457. It then uses the remaining spaces: 10 - 4 = 6 to print the decimal point and the part of the number to the left of the decimal point. Note how the number is rounded when it is printed. The output would look like the following: _ _ _ 9 9 . 3 4 5 7 49

  50. 5.3 Left Justification for double We can use a printf statement to round but use left justification instead. In this example, we will print left justified a floating point value in a field width of 10 with a precision of 4. double percentage = 99.3456789; System.out.printf (“ %-10.4f ”, percentage ); Note how the number is rounded and left justified when it is printed. Any other output will start after the 3 blank spaces. The output would look like the following: 9 9 . 3 4 5 7 _ _ _ 50