On
completion of this section you will be familiar with the structures and uses
of:
The
sequence of our programming has up to now gone from top to bottom. In Listing
1.1 the sequence of execution went from line 6 to line 15 without any
interruption. The same applies to listings 2.1 and 2.2.
Some lines
could be skipped. In Listing 3.1, as the code is currently written the sequence
of execution would be 6, 7, 8, 9, 11, 17, 18, 19, 20, 21, 22. In the same
listing, if line 6 was altered to rate =
20; this would give a gross pay of 800 and thus the sequence of execution
would be 6, 7, 8, 9, 15, 17, 18, 19, 20, 21, 22. Even here, although lines are
skipped, the sequence of execution is still top to bottom.
In loops we
interrupt this top to bottom sequence, because the nature of a loop is that a
group of lines may be repeatedly executed before the line following them gets
executed. Thus a sequence of execution of a group of lines containing a loop
could be:
1, 2, 3, 4,
5, 3, 4, 5, 3, 4, 5, 3, 4, 5, 3, 4, 5, 6, 7, 8
Here we
notice that the lines 3, 4, 5 are executed 5 times before line 6 is executed.
This means that those lines are part of a loop.
Listing
4.1 below contains a for loop that
prints the square and the cube of all numbers between 1 and 10.
Listing 4.1
|
1 |
public class Untitled6 |
|
2 |
{ |
|
3 |
public
static void main(String[] args) |
|
4 |
{ |
|
5 |
int
counter, square, cube; |
|
6 |
for(counter = 1; counter <10; counter++) |
|
7 |
{ |
|
8 |
square = counter * counter; |
|
9 |
cube = square * counter; |
|
10 |
System.out.print("Number " + counter); |
|
11 |
System.out.print(" Square
" + square); |
|
12 |
System.out.println(" Cube
" + cube); |
|
13 |
} |
|
14 |
} |
|
15 |
} |
In line 5
we declare the three variables that we shall be using. The first one, counter, is used to control the loop as
we shall see shortly, while the other two will hold the values of the square
and cube of counter, before being printed.
Line 6 is
where the loop is defined. It begins with the keyword for which indicates what type of loop we are going to use. In
brackets following the keyword are the three components that control the
loop. The first one – counter = 1; - sets the starting value
for the loop, in other words the loop will begin counting at 1. The second
component is a condition that controls the termination of the loop. It is a
condition – counter < 10; – in
this case. As long as this condition is true the loop will keep on going. The
final part – counter++ - indicates
how the value of the loop counter will change. In this case it is incremented
by 1.
Let us now
look at a line by line execution. When line 6 is first encountered the variable
counter is initialised to 1. The
condition is then checked for being true. Since 1 is less than 10 then it is
true and thus the body of the loop is executed. This lies between lines 8 and
12. First the square and cube of 1 is calculate at lines 8 and 9 – both being
1. Lines 10 – 12 prints out the values of counter and its square and cube. The
output of the three lines would be:
Number
1 Square 1 Cube 1
Note: Lines
10 and 11 has System.out.print while
line 12 has the more familiar System.out.println.
What is the difference? When we use println
then the next item to be printed will be on a new line. With print all subsequent printing will be
on the same line as the current printing.
By the time
we have reached line 12 we are at the end of the body of the loop and instead
of proceeding down the rest of the code, control is passed back to line 6. Here counter
is incremented to 2, the condition is checked for being true and since it is
the body of the loop is executed once more – this time printing out
Number
2 Square 4 Cube 8
This
continues until counter is
incremented to a value of 9. Once this occurs the condition is checked once
more, and found to be true since 9 is less than 10. The body of the loop is then entered, finally
printing the line
Number
9 Square 81 Cube 729
Control
once more passes to line 6 where counter
is incremented to 10. When the condition counter
< 10 is now checked it is found to be false since 10 is not less than
10. This will cause the loop to terminate and control will pass from line 6 to
line 14, which eventually terminates the programme.
Looking at
listing 4.1 we notice that the body of the loop is enclosed in curly brackets
in lines 7 and 13, just as the bodies of the if and else were in
Chapter 2. On the other hand, if the body of the loop contained only one line
then we could dispense with the curly brackets as listing 4.2 shows us.
Listing 4.2
|
1 |
public class Untitled7 |
|
2 |
{ |
|
3 |
public
static void main(String[] args) |
|
4 |
{ |
|
5 |
int
counter; |
|
6 |
for(counter = 1;counter < 10;counter++) |
|
7 |
System.out.println(counter); |
|
8 |
} |
|
9 |
} |
In this
case the body of the loop consists of only line 7, so without the brackets the
system presumes that this line, and this line only, forms the body of the loop.
Before
leaving the for loop we shall look
at a very simple application for it, which is to add up all of the numbers
between 1 and 10. Obviously changing 10 to any other number would add up the
numbers between 1 and that other number. The code is shown in Listing 4.3 below
Listing 4.3
|
1 |
public class Untitled12 |
|
2 |
{ |
|
3 |
public static
void main(String[] args) |
|
4 |
{ |
|
5 |
int
counter, sum; |
|
6 |
sum =
0; |
|
7 |
for(counter=1;counter<=10;counter++) |
|
8 |
sum+=counter; |
|
9 |
System.out.println(sum); |
|
10 |
} |
|
11 |
} |
At line 5
we declare two variables, counter
and sum. As before the variable counter will serve as our loop counter,
while sum will hold the sum of all
of the values of counter.
At line 6 we initialise the variable sum to zero. Next we encounter the for loop itself at line 7. The loop is programmed to begin counting at 1 and to count up as far as and including 10.
Since the body of the loop is restricted to one line there is no need for curly brackets – although they can be used if you so wish.
The logic of the programme is as follows. The variable counter starts off with a value of 1. At line 8 the variable sum is updated to 1. Back at line 7 counter is incremented to 2 and when control goes to line 8 again sum is now updated to 3, in other words the current value of counter is added to the previous value of sum. Next time 3 will be added to sum giving it a value of 6 and then 4 will be added to it giving it a value of 10. this process will continue until eventually 10 will be added to it giving it a final value of 55.
Listing
4.4 below shows the structure of a while
loop.
Listing 4.4
|
1 |
public class Untitled10 |
|
2 |
{ |
|
3 |
public
static void main(String[] args) |
|
4 |
{ |
|
5 |
int
counter, square; |
|
6 |
counter
= 10; |
|
7 |
while(counter >=0) |
|
8 |
{ |
|
9 |
square = counter * counter; |
|
10 |
System.out.print("The square of "+counter); |
|
11 |
System.out.println(" is "+ square); |
|
12 |
counter--; |
|
13 |
} |
|
14 |
System.out.println("End of output"); |
|
15 |
} |
|
16 |
} |
In this
example of a while loop we want the
loop to count down from 10 to 0 and for each value to print the square of that
value. To commence we initialise the value of counter to 10 at line 6.
This is referred to as priming
the counter. At line 7 we meet the start of the loop control itself with the
keyword while. After the keyword is
the condition of the loop, which in this case specifies that the value of the
counter must be greater than on equal to 0. As we have just set the value of
the counter to 10 the condition is true and thus the body of the loop, which
extends from line 9 to line 12, is entered. The value of square is calculated at line 9 while lines 10 and 11 print out the
formatted result of the calculation. In line 12, however we meet a very
important part of the while loop – altering the value of the loop counter. Here
it is decreased by 1, and thus it will now have a value of 9.
Since we
have reached the end of the body of the loop, control passes back to the start
at line 7, where the value of counter
is tested once more. As the condition is still true the body of the loop is
entered once more. Part of the processing that will occur is that counter will be decreased to 8.
Eventually counter will be decreased to 0. When
this is tested at line 7 the condition will still be true and thus the body
will be entered. Once line 12 is reached the value of counter will be changed to -1. Control will now pass back to line 7
where the value is tested once more. For the first time the condition will be
false since -1 is less than 0. Since the condition is false the loop terminates
and control passes from line 7 to line 14.
We thus see
that the while loop has the same
three components as the for loop,
except that they are distributed differently through the body of the construct.
At line 6 the counter is initialised, the condition for entering the body of
the loop is tested at line 7, while the value of the counter is altered at line
12. The latter is where most beginner
programmers most frequently make mistakes. If counter—was omitted in listing 4.3 then the condition at line 7
would always be true and thus the loop would continue forever.
The final
loop construct, the do..while loop,
appears in listing 4.5 below.
Listing 4.5
|
1 |
public class Untitled11 |
|
2 |
{ |
|
3 |
public
static void main(String[] args) |
|
4 |
{ |
|
5 |
int
counter, square; |
|
6 |
counter = 10; |
|
7 |
do |
|
8 |
{ |
|
9 |
square = counter * counter; |
|
10 |
System.out.print("The square of "+counter); |
|
11 |
System.out.println(" is "+ square); |
|
12 |
counter--; |
|
13 |
}while(counter>=0); |
|
14 |
System.out.println("End of output"); |
|
15 |
} |
|
16 |
} |
As in the
previous example the loop counter is initialised at line 6, although, in the
case of the do..while loop this is
not always necessary. The construct itself starts at line 7 with the keyword do.
The body of the loop spans lines 9 – 12. At line 12 the value of the
counter is altered by subtracting 1 from it. Although initialising the counter
is not necessary , altering it inside the body of the loop is necessary.
At line 13
the condition for the loop is tested for the first time. If the condition is
true then control is passed back to line 7 where the loop commences once more.
If the condition is false then control passes to line 14.
Note
carefully the syntax of the do..while
loop, especially its last line. Notice that the keyword while is outside the closing curly bracket. As in the case of the while loop itself the condition of the
loop follows the keyword and is enclosed in brackets. The most unexpected feature, however, is the
semi colon at the end of the line. This
appears to contradict what we said earlier about not having semi colons after
the bodies of constructs. Notice for
example in listings 4.1 and 4.3 that there is no semi colon after the body of
the loops. In the present case, however,
the closing curly bracket which signified the end of the loop is followed by
the keyword while and this in turn
is followed by the condition of the loop. Since the body of the loop has
already been closed off, the only way we can close off the condition is by
putting a semi colon after it.
All loops
are used to repeat a group of command lines a number of times. Each loop must
have a keyword to indicate what type of loop it is, a counter that keeps track
of how often to go around the loop, a part that initialises the counter, a
part that alters the counter and condition that tests the value of the counter
to see if it has reached its minimum or maximum.
In the for loop the keyword is followed by a
set of brackets which contain the initialising of the counter, the condition
that tests if the counter has reached minimum or maximum value and the
incrementing or decrementing of the counter.
In the while loop the initialising of the
counter is done outside the body of the loop in a separate command line. The
condition of the loop is between brackets following the keyword. The part for
altering the value of the counter is inside the body of the loop. It usually
occurs on the last line of the body but this is not absolutely necessary.
In the do..while loop the counter may be
initialised either outside the body of the loop or inside the same body. If it
is initialised inside the body of the loop then it is the same command that
initialises it as changes its value subsequently. The condition of the loop is tested after the
end of the loop’s body.
Copy Listing
4.1 into your computer then compile and run it. Next change the lower and
upper limits of the loop a number of times and after each change compile and
run again. An example of changing the lower and upper limits would be changing
line 6 to
for(counter = 5; counter <20;
counter++)
Next make
the loop count upwards in units other than 1. Making it count in units of 2 for
example would involve changing the last component inside the brackets to counter+=2. Finally try to make it count backwards by
changing the last component to counter—or
counter-=2.
Perform
similar practices with listings 4.4 and 4.5.
1.
give
a general definition of a programming loop.
2.
describe
the structure of a for loop.
3.
describe
in detail the three components inside the brackets immediately following a for loop.
4.
when
are curly brackets required in the body of a for loop and when are they not required?
5.
what
are the essential components of a while
loop and where are they placed in relation to the structure of the loop?
6.
what
are the main logical differences between a while
loop and a for loop?
7.
what
are the essential components of a do..while
loop and where are they placed in relation to the structure of the loop?
8.
what
are the similarities between the while
and the do..while loops?
9.
what
are the differences between the while
and the do..while loops?
Write a
programme, using a for loop, that
adds up all of the numbers between 1 and 100. The programme will only print out
the final sum, and not the intermediate calculations.
Repeat
Exercise 4.2, except this time use a while
loop.
Repeat
Exercise 4.2 again for a do..while
loop.