Download presentation
Presentation is loading. Please wait.
Published byAlison Wilkinson Modified over 6 years ago
1
Chapter 4 – Loops Dr. Larry G. Thomas – University of Toledo / LCCC
Most of the material in this file is derived from Introduction to Java Programming, 8th Edition by Daniel Liang
2
§4.1 Introduction So far, all of our code has been sequential
The program starts at the top, and proceeds towards the bottom if and switch statements may allow us to skip over some lines of code, but we're still constantly moving down towards the bottom of the program Loops allow us to repeat one or more lines of code as many times as we want
3
§4.1 Introduction Suppose we want to print a table of the square roots of the integers from 1 to 100: System.out.println(1 + ":square root = " + Math.sqrt(1)); System.out.println(2 + ":square root = " + Math.sqrt(2)); System.out.println(3 + ":square root = " + Math.sqrt(3)); System.out.println(4 + ":square root = " + Math.sqrt(4)); System.out.println(5 + ":square root = " + Math.sqrt(5)); … There must be a better way! There is – use a loop
4
§4.1 Introduction Java has three types of loop that we can use to execute code over and over: while do…while for
5
Section 4.2 The while Loop
6
§4.2 The while Loop The syntax of the while loop: while (condition) {
statement(s); } As with the if-then and if-then-else statements, if statement(s) consists of a single statement, then the braces are optional. The statement(s) will continue to be executed as long as condition remains true
7
§4.2 The while Loop while (condition) { statement(s); }
Think of the while loop as running until (!condition)
8
Loop continuation condition
§4.2 The wihle Loop The square root problem: int count = 1; while (count <= 100) { System.out.println( count + ":square root = " + Math.sqrt(count)); count++; } One pass through the body of the loop is called an iteration Loop continuation condition Loop Body
9
§4.2 The while Loop In the square root problem, we knew how many times we wanted the loop to execute, so we counted each iteration This is an example of a counter-controlled loop In the case of a counter-controlled loop, we must increment the counter in each iteration, and our loop-continuation-condition must check the counter every iteration Note: some loops will count from a higher starting value down towards 1 (or zero), and we decrement the counter in each iteration
10
§4.2 The wihle Loop Section implements a hi-low number guessing game The program picks a random number between 0 and 100 (inclusive) The user guesses numbers until they guess the number For each user guess, the program tells the user if they are too high or too low
11
§4.2 The while Loop The book reminds us about good programming practice – don't start by writing code! Start by examining the problem, and determining how we can go about solving it We should program incrementally – when we do start writing code, we don't necessarily have to start at the top and write everything all at once, top-to-bottom, in one pass We can write it in pieces, and then assemble the pieces
12
§4.2 The while Loop Loop design strategies:
Identify the statements that need to be repeated (i.e., the body of the loop Wrap the statements in the condition / braces syntax Code the loop-continuation-condition and add the appropriate statements for controlling the loop
13
§4.2 The Hi-Lo Guessing Game (1)
import java.util.Scanner; public class GuessNumberOneTime { public static void main(String[] args) // Generate a random number to be guessed int number = (int)(Math.random() * 101); Scanner input = new Scanner(System.in); System.out.println("Guess a magic number between 0 and 100"); // Prompt the user to guess the number System.out.print("\nEnter your guess: "); int guess = input.nextInt(); if (guess == number) System.out.println("Yes, the number is " + number); else if (guess > number) System.out.println("Your guess is too high"); else System.out.println("Your guess is too low"); }
14
§4.2 The Hi-Lo Guessing Game (2)
import java.util.Scanner; public class GuessNumberOneTime { public static void main(String[] args) // Generate a random number to be guessed int number = (int)(Math.random() * 101); Scanner input = new Scanner(System.in); System.out.println("Guess a magic number between 0 and 100"); int guess = -1; while (guess != number) // Prompt the user to guess the number System.out.print("\nEnter your guess: "); guess = input.nextInt(); if (guess == number) System.out.println("Yes, the number is " + number); else if (guess > number) System.out.println("Your guess is too high"); else System.out.println("Your guess is too low"); }
15
§4.2 The while Loop Rather than counting iterations through the loop, sometimes we want the body of the loop to run some unknown number of times, until something happens We may determine when to exit the loop based on some special value whose only significance is to end the program Such a value is called a sentinel value, and such a loop is called a sentinel-controlled loop
16
§4.2 The wihle Loop Be careful using float or double values as loop control variables Recall that floating point math is not exact!! If your loop is looking for a particular value to determine when to stop, it may never see it, because it's off a little in the 15th decimal place! Rather than using ==, use <= or >=
17
§4.3 The do-while Loop The do-while loop is a subtle variation on the while loop do { Statement(s); // Loop body; } while (loop-continuation-condition);
18
§4.3 The do-while Loop The biggest difference between the while and do-while loops is that checking the condition in a do-while loop follows the loop body; in a while loop, checking the condition precedes the loop body This means that the body of a while loop will execute zero or more times; the body of a do-while loop will execute one or more times In other words, the body of… …a do-while loop is guaranteed to run at least once …a while loop is not guaranteed to run at all!
19
§4.2 The Hi-Lo Guessing Game (2)
import java.util.Scanner; public class GuessNumberOneTime { public static void main(String[] args) // Generate a random number to be guessed int number = (int)(Math.random() * 101); Scanner input = new Scanner(System.in); System.out.println("Guess a magic number between 0 and 100"); int guess = -1; while (guess != number) // Prompt the user to guess the number System.out.print("\nEnter your guess: "); guess = input.nextInt(); if (guess == number) System.out.println("Yes, the number is " + number); else if (guess > number) System.out.println("Your guess is too high"); else System.out.println("Your guess is too low"); } This is a repeat of the slide we saw earlier
20
§4.2 The Hi-Lo Guessing Game (3)
import java.util.Scanner; public class GuessNumberOneTime { public static void main(String[] args) // Generate a random number to be guessed int number = (int)(Math.random() * 101); Scanner input = new Scanner(System.in); System.out.println("Guess a magic number between 0 and 100"); do // Prompt the user to guess the number System.out.print("\nEnter your guess: "); int guess = input.nextInt(); if (guess == number) System.out.println("Yes, the number is " + number); else if (guess > number) System.out.println("Your guess is too high"); else System.out.println("Your guess is too low"); } while (guess != number); }
21
Section 4.4 The for Loop
22
§4.4 The for Loop A counter-controlled loop is usually written in an alternate form – a for loop – rather than as a while loop Functionally, they're the same, but for some operations, the for loop is much clearer to read A counter-based while loop: Initializes the counter, Has a condition it tests before each iteration, and Modifies the counter each iteration So does a for loop!
23
§4.4 The for Loop Let's revisit our square roots of 1-100 program:
int count = 1; while (count <= 100) { //compute & output sqrt count++; } We can do the same thing with a for loop: for (int count = 1; count <= 100; count++) // compute & output sqrt
24
§4.4 The for Loop The syntax of the for loop is:
for (initialize step(s); loop-continuation-condition; update step(s)) { statement(s); } The initialize, condition, and update parts of the for loop are separated by semicolons, and the whole thing must be enclosed in parentheses Typically, they're all coded on the same line
25
§4.4 The for Loop for (initial-action; loop-continuation-condition; action-after-each-iteration) { // loop body; Statement(s); } As with the while loop, it's possible that the body of a for loop is never executed
26
§4.4 The for Loop Because the for loop is almost always used to implement a counter-controlled loop: The initial-action will be to assign the starting value to the loop control variable (i.e., the counter) The loop-continuation-condition will be that the loop counter is less than its final value The action-after-each-iteration will be to increment the loop counter for (i = 1; i <= 100; i++) As we have seen before, if the body of the loop is a single statement, the braces are optional
27
§4.4 The for Loop If the loop counter is only needed within the loop (i.e., it's not some variable that the program needs outside the loop), it's good programming practice to declare the loop counter in the for statement: for (int i = 0; i<100; i++)… Declaring the loop counter in the for statement means that after the loop, the loop variable no longer exists Restricting the visibility of the loop variable, such that it only exists where it is needed, is good practice This is known as the scope of a variable (Chapter 5)
28
§4.4 The for Loop Sometimes, we'll want to do more than one thing to set up the loop. Perhaps we have one counter (i) that needs to count up from 0, and another counter (j) that needs to count down from 100 at the same time We can separate multiple initialization and/or update steps with commas: for (i=1, j=100; i<=100; i++, j--)
29
§4.4 The for Loop These two are equivalent:
for (i=1, j=100; i<=100; i++, j--) { // body statement(s); } i = 1; j = 100; while (i <= 100) i++; j--;
30
§4.4 The for Loop Finally, the three parts of the for statement are all optional, but they're rarely omitted If the initialization or update is omitted, then no initialization or update is performed If the loop-continuation-condition is omitted, it is assume to be true All of the following set up infinite loops: for (;;) { } for (;true;) { } while (true) { }
31
Which Kind of Loop to Use?
Section 4.5 Which Kind of Loop to Use?
32
§4.5 Which Loop to Use? The while and for loops are known as pre-test loops – they test the condition before each iteration of the loop This means the body of these loops will execute zero or more times The do…while loop is a post-test loop – it tests the condition after each iteration of the loop This means the body of a do…while loop will execute one or more times
33
§4.5 Which Loop to Use? Recommendations:
If you need to make sure the body of your loop runs at least once, use do…while If you know ahead of time how many times the body of the loop needs to run – i.e., a count-controlled loop, use for If you need to have the loop run until some event occurs (but there's no way of telling how many times the loop might need to run to get that even to occur), use while or do…while When there's no compelling reason to use a particular kind, use whatever is most intuitive and comfortable
34
§4.5 Common Loop Errors (1) Don't put a semicolon after the parenthesis: for (i = 1; i <= 100; i++); { // loop body } This will execute what we labeled as being the loop body (i.e., what's between the braces) once The loop's REAL body is the null statement created by the semicolon This loop, as written, will do nothing, 100 times
35
§4.5 Common Errors (2) A do…while loop DOES have to have a semicolon after the condition: for (init;cond;update) stmt; for (init;cond;update) { } while(condition) stmt; while(condition) { } do stmt while (cond); do { } while (cond);
36
§4.5 Common Errors (3) Watch the boundary conditions:
for (i = 1; i <= 100; i++) This will execute the body for i = 1 through 100 for (i = 1; i < 100; i++) This will execute the body for i = 1 through 99 for (i = 1; i < 100; i+=2) This will execute the body for i = 1, 3, 5, …, 99
37
Section 4.6 Nested Loops
38
§4.6 Nested Loops When we looked at if-then-else statements in Chapter 3, we said that the statement(s) in the then and else clauses could be any legal Java statement, including another if statement We called this a nested if statement When it comes to loops, the same thing applies; the body of a loop can contain another loop We call this a nested loop When loops are nested, the inner loop runs for each iteration of the outer loop
39
§4.6 Nested Loops for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) System.out.println("hello"); } How many times will this print "hello"?
40
§4.6 Nested Loops for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) System.out.println(i + "," + j); } What will this print?
41
§4.6 Nested Loops Nested loops are often used for tables
The outer loop iterates through the rows The inner loop iterates through the columns of the current row
42
§4.6 Nested Loops – Example (p.129)
System.out.print(" | "); for (int i = 1; i <= 9; i++) System.out.print(" " + i); System.out.println("\n "); for (int row = 1; row <= 9; row++) { System.out.printf("%3d|", row); for (int col = 1; col <= 9; col++) System.out.printf("%4d", row*col); System.out.println(); } | | | | |
43
Keywords break & continue
Section 4.9 Keywords break & continue
44
§4.9 The Keywords break & continue
Normally, you should let the loop control variable handle controlling the execution of a loop There are special occasions during which it makes sense to override the standard loop execution break and continue can be used to alter the flow of code through a loop Using them indiscriminately or improperly can make your code harder to read and debug
45
§4.9 The Keywords break & continue
break aborts execution of a loop The break statement passes control to the first statement after the end of the loop In the case of nested loops, break terminates only the loop in which it appears (unless you use a labeled block) continue can be used to terminate the current loop iteration – control goes to the end of the loop body (directly to checking the loop control condition) continue aborts the current iteration; break aborts the entire loop
46
§4.9 The Keywords break & continue
while loop do…while loop for loop break aborts the whole loop the first statement after the loop is executed next continue aborts (skips the remaining statements in) the current iteration For do…while and while loops, the condition is evaluated; For for loops, the update action is performed and then the condition is checked
47
§4.2 The Hi-Lo Guessing Game (2)
import java.util.Scanner; public class GuessNumberOneTime { public static void main(String[] args) // Generate a random number to be guessed int number = (int)(Math.random() * 101); Scanner input = new Scanner(System.in); System.out.println("Guess a magic number between 0 and 100"); int guess = -1; while (guess != number) // Prompt the user to guess the number System.out.print("\nEnter your guess: "); guess = input.nextInt(); if (guess == number) System.out.println("Yes, the number is " + number); else if (guess > number) System.out.println("Your guess is too high"); else System.out.println("Your guess is too low"); } This is a repeat of the slide we saw earlier
48
§4.2 The Hi-Lo Guessing Game (4)
import java.util.Scanner; public class GuessNumberOneTime { public static void main(String[] args) // Generate a random number to be guessed int number = (int)(Math.random() * 101); Scanner input = new Scanner(System.in); System.out.println("Guess a magic number between 0 and 100"); while (true) // we'll exit when the user guesses correctly // Prompt the user to guess the number System.out.print("\nEnter your guess: "); int guess = input.nextInt(); if (guess == number) System.out.println("Yes, the number is " + number); break; } else if (guess > number) System.out.println("Your guess is too high"); else System.out.println("Your guess is too low");
49
End of Chapter 4 Any Questions?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.