Loops and arrays
> Click or hit Control-Enter to run the code above
What Are Computers Good At?
-
Basic math
-
Simple decision making
-
Doing things over and over again very, very fast
-
And storing data
Loops
We call the process of repeatedly doing the same thing over and over again a loop.
Here’s the simplest loop, although it’s not that useful:
while (true) {
// do something
}
while
The while
loop has two parts:
-
A block of code to repeat
-
A condition that must be true each time the loop is entered
If the condition is false, the block of code is not executed and execution continues after the loop
> Click or hit Control-Enter to run the code above
Unterminated Loops
Now that we’ve acquired the power to make the computer do things repeatedly, we need to make sure it stops…
An unterminated loop will cause your code to hang, or hit a timeout if you are running our tests.
> Click or hit Control-Enter to run the code above
> Click or hit Control-Enter to run the code above
Common Loop Pattern
int index = 0;
while (index < 4) {
System.out.println(index);
index++;
}
The pattern above is very common:
-
Initialize a variable (
int index = 0
) -
Loop until a condition is met (
index < 4
) -
Update the variable inside the block (
index++
)
So common that it has its own special syntax.
for
Loops
int index = 0;
while (index < 4) {
// do something
index++;
}
The while
loop above is equivalent to this for
loop:
for (int index = 0; index < 4; index++) {
// do something
}
> Click or hit Control-Enter to run the code above
> Click or hit Control-Enter to run the code above
Understanding for
Loops
for
loops are a bit more complex than while
loops—but they are also
more common.
Here’s what to keep in mind:
-
Initialization only happens once when the loop is first executed
-
The conditional is evaluated every time the loop block is executed, including the first time
-
The update is performed after each time the block is executed and before the condition is checked
for
Loop Algorithm
Initialize the loop variable.
Then:
-
Check the condition.
-
If the condition is false, continue execution after the
for
loop -
If the condition is true, execute the loop block
-
After the block finishes, update the loop variable
-
Repeat
> Click or hit Control-Enter to run the code above
> Click or hit Control-Enter to run the code above
> Click or hit Control-Enter to run the code above
Incomplete for
Loops
All three parts of a for loop are optional.
int i = 0;
for (; i < 10; i++) {
// do something
}
for (; i < 10; ) {
// do something else
}
for (;;) {
// do something forever
}
Don’t do this unless you have a good reason.
If You Get Confused
If you get confused by a for
loop, try rewriting it as a while
loop.
That may help clear things up.
Controlling Loop Execution
There are two important control statements that we can use with loops:
-
break
: immediately exit the loop -
continue
: return to the top of the loop, perform the update, and continue if the condition is still true
> Click or hit Control-Enter to run the code above
break
break
is commonly used when you are looking for something using a loop and
want to exit when you find it.
(We’ll talk about arrays in a few slides and this will make more sense.)
> Click or hit Control-Enter to run the code above
continue
continue
is commonly used when you only want to execute the loop for some
values.
What would be another way to accomplish this?
> Click or hit Control-Enter to run the code above
Questions About Loops?
Multiple Data Values
So far we’ve been talking about single data values.
-
Java primitive types allow you to represent single numbers (integers or floating point), truth values (true or false), and characters.
-
But what about representing multiple values?
Why Multiple Values?
Can you think of some real things that could be represented as a series of Java’s primitive types?
-
Text, or what we call strings in computer science.
-
DNA, which we can represent as just a limited kind of string.
-
Time series data, like a series of temperatures taken at regular intervals.
-
Music, as a time series of air pressure measurements.
Arrays
A Java array represents a series of zero or more values of the same type.
-
Arrays are our first example of a data structure.
-
Arrays put values in order, one after another.
-
Values in an array also have an index, their position in the array.
Declaring Arrays
Just like other variables, arrays have a name and type.
But when we declare them we use brackets to declare an array instead of a single value.
// A single integer named single
int integer;
// An array of integers named multiple
int[] multiple;
// A single character named one
char one;
// An array of characters named all
char[] all;
Initializing Arrays
When it is declared an array is empty. To use it we have to tell Java how many elements it has.
The size cannot be changed once the array is initialized.
All arrays have a .length
property that we can use to get their size.
// An array of 8 integers named multiple
int[] multiple = new int[8];
System.out.println(multiple.length); // Prints 8
// An array of characters named all
char[] all;
// Initialize all to hold 4 characters
all = new char[4];
Initializing Arrays With Values
We can also assign values to an array when it is initialized:
// An array of the 4 integers 1, 2, 5, 10
int[] multiple = { 1, 2, 5, 10 };
// An array of the characters c, s, !
char[] awesome = { 'c', 's', '!' };
Here we don’t have to specify the size. Why not?
Getting And Setting Array Values
We use the bracket syntax to both get and set array values by index.
int[] twos = { 1, 2, 4 };
System.out.println(twos[0]); // Prints 1
twos[0] = 2;
System.out.println(twos[0]); // Prints 2
System.out.println(twos[2]); // Prints 4
Announcements
-
The second set of Turing’s Craft exercises are due tomorrow (Thursday) by midnight.
-
MP0 is out and due Friday! At this point you should be able to finish all three problems—but we’ll reinforce the concepts on Friday. Office hours until 7PM today.
-
This week’s quiz will cover material from lecture and Turing’s Craft.