Transcript Loops
Loops
In this section we will learn how to repeat a series of instructions using loops
and to use this to do animation:
while Loops
for Loops
Infinite Loops
do ... while Loops
Exiting Loops
Animation
PHY281 Scientific
Java Programming
Loops
Slide 1
while Loops
The real power of computers is their ability to do the same or similar
things many many times. For this you need loops.
One of the simplest loops is the while Loop. This keeps looping as long
as the test condition is true.
while (<test>) {
<statements>
}
Test the
condition
False
int n = 0;
int sum = 0;
while (n < 20) {
sum = sum + n;
n++;
}
True
Body of
the loop
The loop does not necessarily execute at
all if the test condition is never met.
PHY281 Scientific
Java Programming
Loops
Slide 2
Parallel Lines
import java.awt.*;
import java.applet.*;
Initialise
counter
public class Lines extends Applet {
public void paint(Graphics g) {
int n = 0;
int x = 20;
int y = 20;
while (n < 20) {
g.drawLine(x, y, x + 200, y);
y = y + 10;
n++;
}
}
}
PHY281 Scientific
Java Programming
Loops
Test
counter
Loop
Increment
counter
Slide 3
for Loops
The most powerful loop is the for Loop.
for ( <initialize> ; <test> ; <change> ) {
<statements>
}
Initialise
Test the
condition
False
int sum = 0;
for (int n=0; n<20; n++) {
sum = sum + n;
}
True
Body of
the loop
Change
PHY281 Scientific
Java Programming
The loop does not necessarily execute at
all if the test condition is never met.
Loops
Slide 4
A Grid of Lines
import java.awt.*;
import java.applet.*;
Initialise
counter
public class Grid extends Applet {
public void paint(Graphics g) {
int x = 20;
int y = 20;
for (int i=0; i<=10; i++) {
g.drawLine(x, y, x + 100, y);
y = y + 10;
}
y = 20;
for (int i=0; i<=10; i++) {
g.drawLine(x, y, x, y + 100);
x = x + 10;
}
}
Test
counter
Increment
counter
Loop
Reset y
Loop
}
PHY281 Scientific
Java Programming
Loops
Slide 5
The scope of the counter
Normally the counter is declared inside the loop - and cannot be used
outside (this is known as the scope of a variable).
i is declared in the loop
for (int i=1; i<=10; i++) {
g.drawString("i = " + i, 50, i*10);
sum += i;
}
g.drawString("Sum = " + sum, 50, 120);
g.drawString("i
= " + i, 50, 130);
this gives an error
as i is undeclared
outside the loop
i is declared outside the loop
int i;
for (i=1; i<=10; i++)
g.drawString("i =
sum += i;
}
g.drawString("Sum = "
g.drawString("i = " +
PHY281 Scientific
Java Programming
{
" + i, 50, i*10);
+ sum, 50, 120);
i, 50, 130);
Loops
this is now OK
(i would be 11)
Slide 6
Infinite Loops
If you are not careful you can get the program into an infinite loop
that go round for ever and are hard to break out of.
These all generate infinite loops:
nothing in here
for (;;) {
g.drawString("looping", 50, 50);
}
left out the increment
for (int i=1;i<=10;) {
g.drawString("looping", 50, 50);
}
test is always true
for (int i=1;i>0;i++) {
g.drawString("looping", 50 ,50);
}
PHY281 Scientific
Java Programming
Loops
Slide 7
Floating Point Counters
You may not want the loop counter to increment by integer values. It is perfectly
legal to have a floating point loop counter but is usually undesirable. The reason is
rounding errors. Because floating point numbers are not stored exactly as you add
the increment the number can start to deviate from what you want. It is much
better to use an integer loop counter and convert it.
public class Floop extends Applet {
}
public void paint(Graphics g) {
int x = 20;
int y = 20;
for (double d=0.0; d<=1.0; d+=0.1) {
g.drawString("d = " + d, x, y);
y = y + 10;
}
for (int i=0; i<=10; i++) {
double d = i/10.0;
g.drawString("i = " + i + " d = " + d, x, y);
y = y + 10;
}
}
PHY281 Scientific
Java Programming
Loops
d is not always
exactly what
you want
i is always
exactly what
you want
i is converted
into d each time
so errors don't
accumulate
Slide 8
do ... while Loops
A very similar loop to the while loop is the do ... while Loop. The only
difference between this and the while Loop is that the conditional test
is at the end.
do {
<statements>
} while (<test>) ;
Body of
the loop
Test the
condition
int sum = 0;
int i = 1;
do {
sum += i;
i++;
} while (i <= 10);
False
True
Unlike the while Loop the do ... while Loop is guaranteed to loop at least
once even if the test always fails.
PHY281 Scientific
Java Programming
Loops
Slide 9
Fibonacci Series
public class Fibonacci extends Applet {
public void paint(Graphics g) {
int x = 10;
int y = 20;
int iprev = 0;
int ilast = 1;
int inext = 1;
g.drawString(" " + inext, x, y);
do {
g.drawString(" " + inext, x, y);
inext = ilast + iprev;
iprev = ilast;
ilast = inext;
x = x + 40;
if (x > 200) {
x = 10;
y = y + 20;
}
} while (inext < 1000);
}
The Fibonacci Series
is the series of
numbers:
1 1 2 3 5 8 13 . . .
where each number
(except the first two)
is the sum of the
previous two numbers.
This program prints
the Fibonacci series
below 1000.
}
PHY281 Scientific
Java Programming
Loops
Slide 10
Exiting a Loop
Normally you exit a loop when the test condition becomes false. However you
might like to stop earlier or skip parts of the loop. You can do this using the
break and continue statements.
break exits the loop immediately. continue stops the current pass through
the loop and starts a new one.
while (<test>) {
<statements>
if (<test1>) continue;
<statements>
if (<test2>) break;
<statements>
}
<statements>
goes to the beginning
of the loop again
goes to the statement
after the loop
Can be any sort of loop for, while, do ... while.
PHY281 Scientific
Java Programming
Loops
Slide 11
Animation
By using combinations of loops and decisions we can produce animations i.e.
produce a picture that changes with time.
One key trick is used in animation to give the impression of movement even
though in practice nothing actually moves. If you draw an object and want it to
appear to move you delete it and draw it somewhere else. If the computer is fast
enough it looks like it moves. For a simple object you can delete it by redrawing it
in the background colour.
The following program simulates a ball bouncing around inside a rectangle. The
movement is simulated by redrawing the ball in the background colour. You can
get the current background colour using:
Color backgroundColour = getBackground();
which is the opposite of setBackground( ).
We move the ball around the screen by incrementing the x and y position.
When it gets to an edge we have to change the sign of the incrementaion.
PHY281 Scientific
Java Programming
Loops
Slide 12
Bouncing Ball
public class Ball extends Applet {
int rectLeft = 50, rectRight = 150;
int rectTop = 50, rectBottom = 150;
int x = rectLeft + 7;
int y = rectTop + 2;
int xChange = 2;
int yChange = 1;
int diameter = 10;
public void paint(Graphics g) {
continued on next page
PHY281 Scientific
Java Programming
Loops
Slide 13
Bouncing Ball Continued
public void paint(Graphics g) {
for (int n=1; n < 1000; n++) {
Draw box
g.setColor(Color.black);
g.drawRect (rectLeft, rectTop,
rectRight - rectLeft, rectBottom - rectTop);
Color backgroundColour = getBackground();
g.setColor(backgroundColour);
Erase previous ball
g.fillOval(x, y, diameter, diameter);
if (x <= rectLeft) xChange = -xChange;
if (x >= rectRight - diameter) xChange = -xChange;
if (y <= rectTop) yChange = -yChange;
if (y >= rectBottom - diameter) yChange = -yChange;
x = x + xChange;
y = y + yChange;
}
}
}
Draw new ball
g.setColor(Color.red);
g.fillOval(x, y, diameter, diameter);
PHY281 Scientific
Java Programming
Loops
Slide 14
Slowing it down
If the animation is too fast we can slow it down by introducing a second loop
inside the first one (this is called nesting) which does nothing except waste
a bit of computer time.
This number controls how
long the animation lasts
public void paint(Graphics g) {
for (int n=1; n < 1000; n++) {
for (int i=1; i<500000; i++) {
}
g.setColor(Color.black);
. . .
This number controls
the speed of the ball
There are better ways of doing this because here the speed
of the ball depends on the speed of your computer.
PHY281 Scientific
Java Programming
Loops
Slide 15
Using sleep
If we use the sleep( ) method the program will wait for the time specified before
continuing. The time spent sleeping should be independent of the speed of the
computer. Unfortunately we have to do some Exception Handling to use it.
This number is the time
import java.util.*;
to sleep in milliseconds
. . .
(2 seconds in this case)
public void paint(Graphics g) {
for (int n=1; n < 1000; n++) {
try {
Thread.currentThread().sleep(2000);
}
catch (Exception e){}
This just means this bit
g.setColor(Color.black);
of the program
. . .
This means we try to execute what
is inside the { } but if it fails for
some reason an Exception is
thrown.
PHY281 Scientific
Java Programming
If an Exception is thrown the code
inside the { } is executed (which in this
case does nothing). Otherwise the
program would crash.
Loops
Slide 16