Title: Chapter 5: Repetition
1Chapter 5 Repetition
- There are many situations where a piece of code
needs to be repeated - Calculations that require doing some arithmetic
operation over and over - For instance, computing factorial or summation
- Processes that require repeating a task
- Such as getting a list of numbers to be averaged
- User requesting that something be done over
- Such as in a menu-driven program
- Verifying proper input and having the input
process repeat if input is incorrect - So we need repetition (iteration) instructions
- In Java, there are 3 types of repetition
instructions - while, do, for
2Example to Motivate Loops
- Recall from chapter 3 we saw how to compute a sum
of values - Lets write an averaging program to compute the
average of 4 exam scores - A portion of this program is shown to the right
int sum 0, count 0
System.out.print("Enter exam score 1 ")
int value Integer.parseInt(key.readLine(
)) sum value
count System.out.print("Enter exam
score 2 ") value
Integer.parseInt(key.readLine( )) sum
value count
System.out.print("Enter exam score 3 ")
value Integer.parseInt(key.readLine(
)) sum value
count System.out.print("Enter exam
score 4 ") value
Integer.parseInt(key.readLine( )) sum
value count
double average (double) sum / count
3Problems with the Example
- There are several problems with the previous
example - First, it seems like a lot of work for a simple
idea - Imagine if you had 10 tests instead of 4?
- Or, if we think of this as averaging any list of
numbers, consider what you would have to do to
average a list of 1000 numbers??? - Second, it is inflexible
- What if the number of scores is variable, the
code presented on the previous slide works for
only and exactly 4 scores! - There should be an easier and better way
- And there is using repetition
4Nature of Repetition Instructions Basic
- All repetition instructions have the same basic
strategy - A boolean expression determines whether to repeat
or not - The boolean expression is just like those seen in
chapter 4 - The instruction tests this condition, if this
test is passed, the body of the loop executes and
the condition is tested again, this continues
until the test is failed - Questions
- Is the expression evaluated before or after the
code executes? - Does the code repeat if the expression evaluates
to true or to false? - Can we replace the expression with some other
structure - recall the switch statement did not use a boolean
expression but instead a list of values - for a loop, we might want to replace the boolean
expression with a range to count between (such as
iteration from 1 to 10) - Can loops be exited prematurely?
5In Java
- The answers to the previous questions differ
between every language - In Java, we have
- Is the expression evaluated before or after the
code executes? - Depends on the type of instruction, while and for
evaluate before and do evaluates after - Does the code repeat if the expression evaluates
to true or to false? - In Java, all 3 types of loops expect the
expression to evaluate to true in order to loop - Can we replace the expression with some other
structure - No, although we will find the for loop to be
flexible - Can loops be exited prematurely?
- Yes, but we should try not to do this as it makes
code more confusing
6While Loop
- The first loop to consider is the while loop
- This is a pre-test loop test the expression
first - If it evaluates to true, execute the
instruction(s) and then repeat the test - The loop continues to execute while the
expression evaluates to true - The expression can be any type of boolean
expression, we will see many variations - Note like the if/if-else statements, the
instruction that follows the condition in the
while loop is expected to be a single instruction
- for multiple instructions, use a block as
with if/if-else
7How the While Loop Works
- Flowchart to the right
- The while loop first tests the condition
(evaluates the boolean expression) - If true, the loops body is executed and the
condition is checked again - If false, the loop is executed the next
instruction after the loop is executed - Prior to reaching the while loop, whatever
variable(s) is(are) tested in the expression must
be initialized
While loop syntax while (expression) instr
uction
8Example
- Heres a loop that will compute the powers of 2
that are less than 1000000 - We start with a variable set equal to 1
- We loop while that variable lt1000000
- Inside the loop, we print the value of the
variable and then multiply it by 2 - Notice that since the loop body is more than a
single statement, we enclose it in to make it
a block
int value 1 while (value lt 1000000)
System.out.println(value) value
2 outputs 1 2 4 8 16 32 64
524288
9Controlling the While Loop
- Four common ways to control a while loop
- Expression is based on a calculation
- when the calculation is complete, loop can exit
- this was the case with the previous example
- Loop increments a counter and the loop exits when
the counter reaches an upper limit - this is known as a counter-controlled loop
- Loop includes a query to the user which asks
should we do this again? and the expression
continues to loop while the user answers yes - this is known as a query-controlled loop
- A variation of the query-controlled loop bases
the decision on whether the user has entered a
continuing value or a stopping value - this is known as a sentinel-controlled loop
- While loops are controlled by boolean expressions
- This expression must be able to change from true
to false when the loop should not be executed
again - How?
10Example Query Controlled Loop
- The partial code to the left contains a
query-controlled loop - Each iteration requires that the user input a
number and then answer whether there is another
number or not - Notice that we must first ask the user before
entering the loop in order for answer to have an
initial value - answer must be initialized
int count 0 int sum 0 int value
double average System.out.print("Do you have
numbers to average? ") char answer
key.readLine( ).charAt(0) while(answer y
answer Y) System.out.print("Ente
r a positive number ") value
Integer.parseInt(key.readLine( )) sum
value count System.out.print("Do
you have numbers to average? ") answer
key.readLine( ).charAt(0) average (double)
sum / count
11Sentinel Controlled Loop
- The problem with the query controlled loop is
- The user is asked for at least two pieces of
information - The input that will be processed in this
iteration of the loop - Whether to repeat or not
- We can combine these inputs
- In our previous example, we averaged a list of
positive numbers - We will use negative numbers as our sentinel
values - Now, we will continue to repeat while the input
is not negative (value gt 0) - This simplifies our loop because we remove four
instructions and may simplify the users ability
to user our program (only requires half as many
inputs) but users are less likely to understand
these instructions!
12Sentinel Controlled Version
int count 0 int sum 0 int value
double average System.out.print("Enter a
non-negative value ") value
Integer.parseInt(key.readLine( )) while(value
gt 0) sum value count
System.out.print("Enter your next non-negative
value ") value Integer.parseInt(key.rea
dLine( )) average (double) sum / count
- Notice that our instructions are not necessarily
explicit enough for the user - We merely ask for the next non-negative value
- A better prompt is
- Enter your next number, (a negative number to
quit)
Again notice that we have to ask the user for a
value before entering the loop to initialize
our loop variable (value in this example)
13Forgetting to Alter the Loop Variable
- The loop variable(s) is(are) the variable(s) that
is evaluated in the while loops boolean
expression - If your loops body does not change that value,
you could be in trouble - Consider the following, which is supposed to
start at 1 and count up to 10, outputting each
value - What will happen?
- The loop does not terminate because the loop
variable never changes from 1 because the
programmer forget to use - (x lt 10) is always true
- This is known as an infinite loop
- The loop literally will run forever (unless you
kill the program) - The infinite loop is a common problem, one you
must be aware of
int x 1 while (x lt 10)
System.out.println(x) x
14Counter-Controlled Loops
- The previous example was a form of a
counter-controlled loop - Although it didnt work because it was an
infinite loop - The counter-controlled loop works as follows
- Initialize your loop variable to the first value
- Compare the loop variable to the last value
- If the last value has not been reached, enter the
loop - Perform the loop
- Before exiting the loop, alter the loop variable
- The loop counts which iteration it is on
- We could then use the loop variable if we need to
have that value as part of a calculation
15Example Computing Factorial
Lets trace through this code for n 5 Before
the loop factorial 1, x 1 Since x lt
5 enter loop 1st iteration factorial 1
1 1, x 2 Since x lt 5 continue 2nd
iteration factorial 1 2 2, x
3 Since x lt 5 continue 3rd iteration
factorial 2 3 6, x 4 Since x lt 5
continue 4th iteration factorial 6 4
24, x 5 Since x lt 5 continue 5th iteration
factorial 5 24 120, x 6 Since x gt 5,
exit
- Factorial of n 1 2 n
- We can use a counter-controlled loop to compute
this - The code is given below
factorial 1 x 1 while (x lt n)
factorial x x System.out.println(
"The factorial of " n " is "
factorial)
16The for Loop
- The counter-controlled loop requires three steps
initialize loop variable(s), test loop
variable(s), alter loop variable(s) - Java also has a for-loop
- This loop specifies all 3 of these activities in
its expression part and so simplifies the task
of writing the loop by the programmer - Javas for-loop is also very flexible so that it
can do non-counting activities as we will see
later on - For now, we will concentrate on using it just as
a counter-controlled loop
17How the for-loop Works
- To the right is the flowchart for the for-loop
- The syntax (shown below) is a little more complex
because the loop does all of the things for us - The syntax shown below assumes that the loop will
be counting for us, we will see other forms of
for-loops shortly
Syntax for(variable initial value variable
lt final value variable variable change)
statement
18For-loop examples
- Iterate 100 times
- for(i0 ilt100 ii1)
- Iterate from 1000 to 1
- for(i1000 igt0 i--)
- Iterate from a to b (a and b are ints)
- for(ja jltb j)
- Iterate from 0 to 1000 by 2s
- for(j0 jlt1000 j2)
- Iterate from 0 to 1000, increasing the step size
by 1 each time (e.g., 0, 1, 3, 6, 10, 15, 21, )
(assume n is initialized to 1) - for(k0 klt1000 k n)
Historic note In early FORTRAN, all variables
floats (called real in FORTRAN) unless the
variable name started with a letter I through
N (I..N for integer) Thus, it was popular to
use i, j, k, , n for loop variables and we
continue to do the same today
19for-loop vs. while loop
- When having to perform some action a known number
of times, we use the for loop instead of the
while loop because it is easier - We dont have to do the initialization or
incrementing, those are done for us! - Example print the square of each integer from 1
to 25
for (value 1 value lt 25 value)
System.out.print(value " squared is "
value value)
value 1 while (value lt 25)
System.out.print(value " squared is "
value value) value value 1
20Additional Loop Examples
- Assume that str is a String, the following prints
the characters of str backwards
If str hi there, then length is 8 although
the positions in the string are numbered 0
7. Starting at 7, going back to 0, print each
character
for (istr.length( )-1igt0i--)
System.out.print(str.charAt(i)) System.out.printl
n()
- And here is a variation of the averaging program
ask the user how many items there are to
average
System.out.println("how many values do you want
to average? ") n Integer.parseInt(key.readLine(
)) for(i1 iltn i)
System.out.println("Enter value i ")
value Integer.parseInt(key.readLine( ))
sum value double average
(double) sum / n
21The for-loop in More Detail
- The Java for-loop consists of three parts
- for (initializer condition increment)
- The for-loop is more flexible than just a
counting loop - initializer, condition, increment are not limited
to numbers - for(ch a ch lt z ch) // iterate over
a series of char values - or, perform input statements from within the
for-loop - for(answer key.readLine( ) !answer.equals("no")
answer key.readLine( )) - any of these three parts can be omitted or have
multiple parts - for(j 0, k x j lt n k gt 0 j) k - j
- This loop will stop once j n or once k lt 0
- for( j lt n j)
- This loop omits the initialization of j assuming
it was done previously
22Break, Continue, Null Statements
- break causes control to exit the current control
structure and can be used in for or while loops
to prematurely exit - continue is a related instruction but branches to
the top of the loop - continue is like break, but rather than exiting
the loop, starts the loop over (if the condition
is still true)
- the null statement is just a
- This is an empty statement that could be used in
a for loop as seen in the previous slide or could
be used to indicate that the loop should do
nothing - for(j 0 j lt 10000 j)
- The null statement can also be used in an if-else
statement if there is no if-clause
All 3 of these statements can cause a program to
be hard to understand, and so should not be used
unless absolutely necessary. There are ways to
achieve each of these without resorting to these
operations see the examples on the next slide
23Examples
if(x lt y) else x y Can be rewritten as
if(x gt y) x y for(j0 jltn )
j Can be rewritten as for(j0 jltn
j)
while(x lt n) System.out.print("Enter
next number ") x Integer.parseInt(key.rea
dLine( )) if(x lt 0) break else sum
x Can be rewritten as while(x lt n x gt
0) System.out.print("Enter next number
") x Integer.parseInt(key.readLine( ))
if(x gt 0) sum x
Except for using break in the switch statement,
you are discouraged from using any of break,
continue or null
24Nested Loops
- The outer loop will initialize the sum to 0 and
then enter the inner loop - The inner loop will input a number, add it to the
sum and increment count, asking for the next
number - Upon exiting the inner loop, the outer loop
calculates and outputs the average, and asks if
the user wants to do another set or not - We can have as many nestings of loops as we want
- Just as we had nested if-else statements, we will
often want to have nested loops - In this case, we nest loops when there are things
we need to repeat repeatedly - We might want to create an averaging program that
allows the user to enter multiple sets of numbers - The user inputs a set of numbers ending with a
negative number, and the average is computed - The program asks the user if he/she wants to do
another set, and if yes, the entire process is
repeated
25Using 2 While Loops
import java.io. public class Averager
public static void main(String args) throws
IOException int num, sum, count
double average
BufferedReader key new BufferedReader(new
InputStreamReader(System.in))
System.out.print(Do you want to average a set of
numbers? (Y/N) ") String answer
key.readLine( ) while
(answer.charAt(0) Y answer.charAt(0)
y)
System.out.print("Enter your first number
") num Integer.parseInt(key.readLine(
)) while (num gt 0)
sum num
count
System.out.print("Enter your next number
(negative to end) ") num
Integer.parseInt(key.readLine( ))
if (count gt 0) average (double) sum
/ count else average 0.0
System.out.println("for the " count " values
entered ")
System.out.println(" the average is "
average) System.out.print("D
o you want to average another set of numbers?
(Y/N) ") answer key.readLine( )
System.out.println("Goodby
e! ")
Outer Loop controlled by users
answer Inner Loop controlled by sentinel
value
26Nested For Loop Examples
- If n 5, this outputs
- 2 3 4 5
- 4 6 8 10
- 6 9 12 15
- 8 12 16 20
- 10 15 20 25
- Notice that it doesnt
- quite line up!
for(i0iltni) for(j0jltnj)
System.out.print(" " ij)
System.out.println()
for(i0iltni) for(j0jlti1j)
System.out.print("") System.out.println()
If n 5, this outputs
27Nested for Loops Continued
- The basic idea behind a nested for loop is that
the inner loop works through all of its
iterations for each outer loop iteration - See the figure to the right for the two loops
- In general, such nested loops iterate n m times
where n is the number of iterations for the inner
loop and m is the number of iterations for the
outer loop - For instance, the above loop will iterate a total
of 4 n times
for(i1 iltn i) for(j1 jlt4 j)
28Example Prime number
import java.io. public class PrimeNumberComputer
public static void main(String args)
throws IOException BufferedReader key
new BufferedReader() int i, num,
limit boolean prime true
System.out.print("Enter a number, I will see if
it is prime ") num Integer.parseInt(key.re
adLine( )) for(i2iltnumi) if (num i
0) prime false if (prime)
System.out.println(num " is a prime number.
") else System.out.println(num " is not
a prime number. ")
An improvement Change the for loop to
iterate from 2 to num/2 or even better
Change the for loop to a while loop Why
would this be an improvement?
if (num i 0) it means that num is divisible
by i, and since i ! 1 and i ! num, then num
has a divisor not equal to 1 or itself
29do-while loop
- The final loop is like the while loop except that
the test comes at the end of the loop - This is known as a post-test loop
- It is safer to use a while loop because there are
many occasions where we wont know if we even
want to enter the loop until we perform the
boolean test - The do-while loop is less safe we are assuming
we want to enter and execute the loop body at
least once - So, we will use this loop instead of the while
loop when we know that we want to execute the
loop body at least one time - There are a few applications, the primary one is
for data verification
30The do-while Loop
- As seen to the right, the loop is entered, the
statements are executed, and then the condition
is tested - If true, the loop is repeated
- If false, the loop is exited and the next
statement is executed
do-while syntax do statement
while (condition) Like all Java statements, if
the statement consists of multiple instructions,
place them within
31Example Data Verification
- Consider a situation where you ask the user to
input a value within a certain range and expect
the user to follow instructions - If the user does not follow instructions, will
your program still work correctly (or at all)? - One example is a program that takes a square root
the input number must be non-negative - See examples to the right
System.out.print("Enter a non-negative number
") int x Integer.parseInt(key.readLine( ))
double sq Math.sqrt(x) System.out.println("The
square root of " x " is " sq)
This code could lead to a run-time error but this
code fixes the problem
do System.out.print("Enter a
non-negative number") int x
Integer.parseInt(key.readLine( )) (while x lt
0) double sq Math.sqrt(x)
System.out.println("The square root of " x
" is " sq)
32Data Verification Logic
- Note that data verification can also be
accomplished using a while loop but this code is
a little longer - See example to the right
- We must be careful in deriving the boolean
expression for data verification - What if we want to ensure that the user has
entered one of two valid responses such as Y/N?
System.out.print("Enter a non-") int x
Integer.parseInt(key.readLine( )) while(x lt 0)
System.out.print("I said NON-NEGATIVE! ")
x Integer.parseInt(key.readLine( ))
The advantage of the while loop is that
we can alter the prompting message to
explain what the user did wrong
Example condition do // request user to enter
Y or N while (answer ! Y answer ! N)
33Menu Driven Programs
- We now have the proper tools to put together a
menu driven program if we choose to - What is a menu driven program?
- The user is able to select what the program
should do from a menu - Repeat the following
- The menu is displayed
- The user selects a choice
- If legal, the proper operation is performed, if
illegal, an error message is displayed - Until the user selects the quit option
- We will use a do loop to implement the repetition
- We will use a switch statement to select the
operation based on the users choice
34Menu Driven Example
// assume num is an int variable, previously
input System.out.print("Enter 1 for square, 2
for square root, 3 for prime ") " 4
for new number, 5 to quit ")) choice
Integer.parseInt(key.readLine( )) while
(choice ! 5) switch (choice)
case 1 System.out.println("Square is "
num num) break case 2 System.out.println(
"Square root is " Math.sqrt(num)
break case 3 / place prime number code
here / break case 4 System.out.print(Ente
r new number ) num Integer.parseInt(key.r
eadLine( )) break case 5 System.out.println("
Thanks for using calculator ")
break default System.out.println("Incorrect
choice, try again! ")
System.out.print("Enter 1 for square, 2 for
square root, 3 for prime ") " 4 for
new number, 5 to quit ")) choice
Integer.parseInt(key.readLine( ))
- Consider a simple example
- given an input value, the user can either have
the program compute the numbers square, square
root, if it is prime or not, input a new number,
or quit
35Example Counting vowels
import java.io.public class CountVowels
public static void main (String args) throws
IOException BufferedReader key new
BufferedReader(new InputStreamReader(System.in))
int i, j, count String input, vowels vowels
new String("aeiou") count
0 System.out.println("Enter a string and I will
count the number of vowels") input
key.readLine( ) input input.toLowerCase(
) System.out.println( ) for (i0
iltinput.length( ) i) for (j0 jlt5
j) if (input.charAt(i) vowels.charAt(j))
count System.out.println(input " has "
count " vowels in it")
36Common Errors
- Off-by-one errors having your for-loop iterate
the wrong number of times - It is common to use the following format in Java
- for(j 0 j lt n j) or for(j 1 j lt n
j) - but using
- for(j 0 j lt n j) or (j 1 j lt n j)
- Will lead to your loop iterating 1 too many or 1
too few times! - Improper use of
- Be careful with your boolean expressions and also
make sure that you properly compare Strings,
objects, doubles and floats for equality