Lesson 8:
Loops -
Repeatedly execute a sequence of statements
- The do loop repeatedly executes the statements as long as the
boolean expression is true.
do
... statements ...
while ( boolean expression) ;
- The while loop repeatedly executes the statement (or statements if
enclosed in { } ) as long as the boolean expression is true. Similar to the do
loop except that the boolean expression is tested before the
statements are executed (and may cause the loop to terminate immediately).
while ( boolean expression)
statement
- The for loop performs an initial statement before the loop
is started. The test expression is evaluated on each pass
through the loop and the loop exits if it is false. If the test
expression is true, the loop body is performed, after which the iteration
expression is executed.
for ( initial statement ; test expression ; iteration expression)
statement
Arrays - An indexed collection of data elements, all of the same
type
- To declare an array we specify the type of the elements in
the array followed by [] and the name of the array.
type [] arrayName;
- To create an array we can use the new command with the type
and size of the array or we can specify initial values enclosed in { }.
arrayName = new type[ size ];
or
arrayName = { value of element 0, value of element 1,
... }
- To use an array element we give the array name followed by the
index enclosed in [ ].
arrayName [ index ]
Try this:
- Take a look at the file Loop1.java from the web page. Try it
out. Be sure you try entering both positive and negative values for
the loop termination.
- Change the code so that the applet counts down from the entered value down
to 0.
- Change the code so that it behaves the same way but uses a for loop rather
than a while loop.
- Here is an interesting mathematical function: suppose you have a value
x. If x is even, the function returns x/2. If x is odd, the
function returns 3x+1. If we iteratively apply this function to
numbers larger than 1, mathematicians believe the sequence of values
eventually returns to 1. Write a little program (you can use
Loop1.java as a starting point) in which the user enters a starting number
and then we loop and print out the values as long as x is not equal to 1.
- Take a look at the file Array1.java from the web page. Try it
out. Be sure to try search for values that are in the array and values
that are not.
- Change the code so the the applet prints ALL the locations that the target
value is found. You can print to the console if you wish.
- Change the code so that you add a second array with indices from 0 to
9. Use that second array to count the frequency of the values in the
original array. For example, the value 3 appears twice in the
original array so your array at index 3 would have the value 2. Print the
frequencies after they are all computed to the console.