Title: Repetition
1Repetition
- What happens if we want to do some action
multiple times? - For instance, we want to compute multiple
students grades? - We could run our grade program several times
- But this is tiresome and also does not allow us
to compute things like class averages or sort the
scores or anything like that - We instead need instructions that allow code to
be repeated thus repetition control statements - There are three forms of repetition statements in
Java - While loops
- Do loops
- For loops
2The While Statement
- The while statement evaluates a condition
- if that condition is true, the body of the while
statement is executed and the process is repeated - If the condition is false, the rest of the
statement is skipped and control continues with
the next instruction after the while statement
3Example
- Lets write 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
4Sentinel Values
- In the prior example, we iterated until we
reached an upper limit - We will often use While loops to repeat some
action such as input some value, perform a
calculation, output a result, repeat until the
user is done - How do we know if the user is done?
- We could ask the user or we could base the
decision on the input value this is known as a
sentinel value - Example input a list of integers until the user
enters a negative number, and compute the sum of
these numbers
5Sum Example
int value, sum sum 0 value
Integer.parseInt(JOptionPane.showInputDialog
(null, Enter a positive integer, negative
number to quit)) while (value gt 0) sum
value value Integer.parseInt(JOptionPa
ne.showInputDialog (null, Enter next positive
integer, negative number to quit)) System.out
.println("The sum of the numbers you entered is
" sum)
Initialize sum before we enter the loop
value lt 0 is our sentinel for the loop
Notice that we repeated these Instructions why?
6A slightly different version
int value, sum sum 0 value
Integer.parseInt(JOptionPane.showInputDialog
(null, Enter a positive integer, negative
number to quit)) while (value gt 0) sum
value System.out.println("The sum of the
numbers you entered is " sum)
Notice in this version we dont ask for the next
value this means that value never changes if
it never changes, then it is always the original
value, if that value was gt 0, it will always be
gt 0 and thus the loop will never stop this is
an infinite loop
7Infinite Loops
- Careless (and even careful) programmers will
write infinite loops - This is a major problem when using the while loop
- The basic idea behind the loop is to continue
executing while a condition is true - If that condition is based on an input value,
then the program must input a new value during
each iteration so that the user can change the
value to one that exits the loop - Otherwise, the value never changes and the loop
never stops! - Exiting an infinite loop
- if you suspect that your program is caught in an
infinite loop, about your only recourse is to
stop the program - Press control-C on the keyboard
8Computing an Average
int number, count, sum float average sum
0 count 0 number Integer.parseInt(JOptionPan
e. showInputDialog(null, Enter a number, 0
to end)) while (number gt 0) sum
number count number
Integer.parseInt(JOptionPane.
showInputDialog(null, Enter a number, 0 to
end)) average (float) sum /
count System.out.print("The average of your "
count) System.out.println("numbers is "
average)
This program is similar to the sum program from
before, but we are also counting the number of
inputs using the count variable 0 (or any
negative number) is our sentinel
value Notice that average is not
formatted, our output might look messy!
9The do Loop
- The do loop is similar to the while loop but is a
post-test loop, the while loop is a pre-test loop - The Do loop starts with the reserved word do
followed by the loop body and then the reserved
word while and the condition - The difference is the flow of control here, the
condition is not evaluated until after the body
of the loop executes
10While vs. Do
- The only difference between these two statements
is when the condition is evaluated - While evaluated before executing the loop body
- Do evaluated after executing the loop body
- If you want to automatically execute the loop
body at least once, use the Do loop - If you dont want to do the body if the condition
is not true, use the While loop
11Using Loops to Verify Input
- Consider a situation where we want the user to
input one of a set of values that constitute a
legal input - What if the user enters an illegal input?
- Example input a non-negative integer and take
the square root - If x lt 0, we would get a run-time error when the
sqrt operation is invoked!
- A solution to this problem is to place the prompt
and input statements inside a loop that only
terminates once the user has entered the right
value - We will use a do statement for this since we will
want the user to input the value at least one time
x Integer.parseInt(JOptionPane.showInputDialog(n
ull, "Enter a non-negative integer ")) y
Math.sqrt((double) x)
do x Integer.parseInt(JOptionPane. s
howInputDialog(null, "Enter a non-negative
integer ")) while (x lt 0) y
Math.sqrt((double) x)
12for Loop
- The While and Do statements are most commonly
used when the condition is based on an input
that is, the user will decide whether to execute
the loop again or not - In another situation, we might have a limit on
the number of times we want to execute the loop
body then we will use the for loop - The for loop is sometimes referred to as a
counting loop - it counts the number of iterations performed
- We can make the for loop count from 1 to 10,
from 1000 down to 1, from 0 to 100 skipping every
other number, - In fact, the for loop provides so much
flexibility that we can have it do the same thing
that a while loop does
13Structure of a for loop
Initialize the loop variable(s) Check the
condition if true, execute the body Perform
the increment which might alter the condition
14For loop examples
- Iterate 100 times
- for (int i 0 i lt 100 i i1)
- System.out.println(i)
- Iterate from 1000 to 1
- for (i 1000 i gt 1 i i-1)
- System.out.println(i)
- Iterate from a to b (a and b are ints)
- for (int j a j lt b j)
-
- Iterate from 0 to 1000 by 2s
- for (j 0 j lt 1000 j 2)
-
15Using the for 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 more convenient and
readable - - 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
16Another for loop example
- Here is a variation of the averaging program
first ask the user the number of items to average
x Integer.parseInt(JOptionPane.showInputDialog
(null, "How many numbers do you have to
enter? " )) for (i0 iltx i) num
Integer.parseInt(JOptionPane.showInputDialog
(null, "Enter value " i ))
sum num average ((float) sum) / x
17For loop with graphics
Draw a series of circles
private static class GraphicsPanel extends
JPanel protected void paintComponent(Graphics
g) super.paintComponent(g) for
(int i 1 i lt 20 i) g.drawOval(i20,
300, 10, 10)
You can download this program from the course web
site. Then lets enhance it in a few ways
18Another for loop with graphics
Draw striped flag
protected void paintComponent(Graphics
g) super.paintComponent(g) g.drawRect
(150, 100, 500, 300) for (int i 0 i lt 15
i) if (i 3 0) g.setColor(Color.RED)
else if (i 3 1) g.setColor(Color.YELLO
W) else g.setColor(Color.BLUE) g.fill
Rect(150, 100i20, 500, 20)
19Draw a single star
protected void paintComponent(Graphics
g) super.paintComponent(g) g.setColor
(Color.red) int x 70, 60, 30, 50, 40,
70, 100, 90, 110, 80, 70 int y 30, 50,
50, 65, 90, 80, 90, 65, 50, 50, 30
g.fillPolygon(x, y, 11)
20Draw a sequence of stars
protected void paintComponent(Graphics
g) super.paintComponent(g) for
(int i 0 i lt 11 i) // Draw a
star. int shift i100 g.setColor(Color.red)
int x 70shift, 60shift, 30shift,
50shift, 40shift, 70shift, 100shift,
90shift, 110shift, 80shift,
70shift int y 30, 50, 50, 65, 90, 80,
90, 65, 50, 50, 30 g.fillPolygon(x, y, 11)
21Nested For Loop Example
- 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 (i 1i lt5 i) for (j 1 j lt5
j) System.out.print(" " ij)
System.out.println()
22Graphics Using Nested For Loops
protected void paintComponent(Graphics
g) super.paintComponent(g) g.setColor(new
Color(128, 128, 255)) g.fillRect(0, 0, 700,
700) g.setColor(Color.BLACK) g.drawRect(100,
100, 400, 400) for (int i 0 i lt 8
i) for (int j 0 j lt 8 j) if
((ij) 2 0) g.setColor(Color.GREEN)
g.fillRect(100i50, 100j50, 50,
50) else g.setColor(Color.RED)
g.fillOval(100i50, 100j50, 50,
50)
Green rectangles and red circles in a grid.