# Loops and Arrays

Tom Kelliher, CS 116

Nov. 4, 2002

Exam Friday.

### From Last Time

Quiz, finished Lab 6.

1. Loops.

2. Arrays.

3. Exercise

Lab 8.

# Loops

Repeatedly execute a sequence of statements .

1. The do loop repeatedly executes the statements as long as the boolean expression is true.
```do
... statements ...
while (boolean expression);
```

2. 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;
```
or
```     while (boolean expression)
{
... statements ...
}
```

3. 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.

1. To declare an array we specify the type of the elements in the array followed by `[]` and the name of the array.
```type [] arrayName;
```

2. 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, ...  }
```

3. To use an array element we give the array name followed by the index enclosed in `[ ]`.
```     arrayName[index]
```

# Exercise

Refer to handout.

Thomas P. Kelliher
Wed Oct 30 16:43:37 EST 2002
Tom Kelliher