Download ch05 - Loops Liang

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
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
§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
§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
System.out.println(2
System.out.println(3
System.out.println(4
System.out.println(5
…
+
+
+
+
+
":square
":square
":square
":square
":square
root
root
root
root
root
There must be a better way!
 There is – use a loop

=
=
=
=
=
"
"
"
"
"
+
+
+
+
+
Math.sqrt(1));
Math.sqrt(2));
Math.sqrt(3));
Math.sqrt(4));
Math.sqrt(5));
§4.1 Introduction

Java has three types of loop that we can use to
execute code over and over:
 while
 do…while
 for
Section 4.2
§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

§4.2 The while Loop
while (condition)
{
statement(s);
}
 Think of the while
loop as running
until (!condition)
§4.2 The wihle Loop

The square root problem:
Loop continuation condition
int count = 1;
while (count <= 100)
{
System.out.println(
count + ":square root = " +
Math.sqrt(count));
count++;
}
Loop
Body
One pass through the body of the loop is called an iteration
§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
§4.2 The wihle Loop
Section 4.2.1 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

§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
§4.2 The while Loop

Loop design strategies:
1. Identify the statements that need to be repeated (i.e.,
the body of the loop
2. Wrap the statements in the condition / braces syntax
3. Code the loop-continuation-condition and add the
appropriate statements for controlling the loop
§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");
}
}
§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");
§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
§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 >=

§4.3 The do-while Loop
do-while loop is
a subtle variation on
the while loop
 The
Statement(s)
(loop body)
true
do
{
Loop
Continuation
Condition?
false
Statement(s); // Loop body;
} while (loop-continuation-condition);
§4.3 The do-while Loop
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
 The
 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!
§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);
This is a repeat of the
slide we saw earlier
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");
§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);
Section 4.4
§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!
§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
}
§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
§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
§4.4 The for Loop
the for loop is almost always used to
implement a counter-controlled loop:
 Because
 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
§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)
§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--)
§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)
{
// body statement(s);
i++;
j--;
}
§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) { }
Section 4.5
§4.5 Which Loop to Use?
while and for loops are known as
pre-test loops – they test the condition before
each iteration of the loop
 The
 This means the body of these loops will execute
zero or more times
do…while loop is a post-test loop – it tests
the condition after each iteration of the loop
 The
 This means the body of a do…while loop will execute
one or more times
§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
§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
§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);
§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
Section 4.6
§4.6 Nested Loops
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
 When
 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
§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"?
§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?
§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
§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();
}
| 1 2 3 4 5 6 7 8 9
---+--------------------------1| 1 2 3 4 5 6 7 8 9
2| 2 4 6 8 10 12 14 16 18
3| 3 6 9 12 15 18 21 24 27
4| 4 8 12 16 20 24 28 32 36
Section 4.9
§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
§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
§4.9 The Keywords break & continue
while loop
do…while loop
for loop
Statement(s)
(loop body)
true
Loop
Continuation
Condition?
false
• 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
§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);
This is a repeat of the
slide we saw earlier
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");
§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");
End of Chapter 4
Any Questions?