Looping
with the array index
A
very common way to process all the elements of an array, is to use a loop
variable for the array index.
The
loop variable must start at 0,
and go up to the <array>.length
value.
However, we must be careful not to attempt to retrieve an element with
index of <array>.length
,
since array index values go from 0
.. (<array>.length - 1).
For
example, to total all the values of a double
array purchases,
we could write the following loop, without having to know how the array
was defined:
double
total = 0;
int index
;
for( index
= 0; index < purchases.length; index++)
total
= total + purchases[ index ];
First we declare
and initialise a double variable total to zero:
int total
= 0;
then we declare
our int index loop variable index:
int index
;
then we start the
loop:
for( index
= 0; index < purchases.length; index++)
Let us assume that
the double array purchases contains the following:
purchases[]
|
element
|
value
|
purchases[0]
|
10.11
|
purchases[1]
|
5.0
|
purchases[2]
|
2.5
|
Then purchases.length
is 3, since there are 3 elements in this array.
Our loop, therefore,
is evaluated at run time to:
for( index
= 0; index < 3; index++)
As the loop iterates
the following happens:
index
|
loop condition
|
total
=
total + purchases[
index ];
|
0
|
0 <
3 = true
|
0 + purchases[0]
= 0 + 10.11
= 10.11
|
1
|
1 <
3 = true
|
10.11
+ purchases[1]
= 10.11 +
5.0 = 15.11
|
2
|
2 <
3 = true
|
15.11
+ purchases[2]
= 15.11 +
2.5 = 15.61
|
3
|
3 <
3 = false
loop terminates
|
|
and the value of
total
after the loop terminates is 15.61.
Back
to top
RITSEC - Global Campus
Copyright © 1999 RITSEC- Middlesex
University. All rights reserved.
webmaster@globalcampus.com.eg
|