Lecture Notes 05: Intro to Loops and 1D Arrays
Objectives
By the end of this module, for simple HelloWorld-like
programs, you will be able to:
- Identify the new syntactic elements with the basic output-only for-loop.
- Demonstrate ability to mentally trace execution of for-loops.
- Produce desired output using for-loop and println's.
- Distinguish between count-up and count-down loops.
- Identify the the patterns that may allow the use of a nested for-loop.
Why is looping useful in computation?
- Being able to process a batch of survey results to do a study
- Searching through a list of webpages to find the ones that match a keyword
- Creating a countdown for a timer for a shopping cart
- Other examples?
Loops: the while-loop
Imagine we wanted to code up a countdown timer:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 |
public class PrintCountdown
{
public static void main(String args[])
{
// Set up an initial count value
double count = 10;
// Now print and decrease it one by one
System.out.println(count--); // "--" acts AFTER we resolve the value, so it prints a 10
System.out.println(count--); // it prints a 9
System.out.println(count--); // it prints a 8
System.out.println(count--); // it prints a 7
System.out.println(count--); // it prints a 6
System.out.println(count--); // it prints a 5
System.out.println(count--); // it prints a 4
System.out.println(count--); // it prints a 3
System.out.println(count--); // it prints a 2
System.out.println(count--); // it prints a 1
System.out.println("Blastoff!"); // it prints Blastoff!
}
}
|
This is tedious...what if there were a way to represent repetition of the same code in Java? Above, we're
executing the identical line of code ten times...Let's see this same idea but with a new structure:
The while loop:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 |
public class AwesomePrintCountdown
{
public static void main(String args[])
{
// Set up an initial count value
double count = 10;
// Now print and decrease it one by one
while (count > 0)
{
System.out.println(count--);
}
System.out.println("Blastoff!"); // it prints Blastoff!
}
}
|
The new structure is:
- the reserved word while
- followed by a boolean condition in perenthesis, in this case "(count > 0)"
- follow by a set of statements inside a block surrounded by curly brackets, in this case the print with count--
The flow of execution for a while statement is:
- Evaluate the condition in parentheses, yielding true or false.
- If the condition is false, skip the following statements in braces.
- If the condition is true, execute the statements and go back to step 1.
Activity 1:
Let's Visualize this execution using our favourite visualizer,
Visualize AwesomePrintCountdown.java
Let's take a minute or two to modify the loop to count in the other direction. Note, that one of the most common mistakes
people make (myself included!) is forgetting to increment/decrement the counter.
If you end up doing this, you'll see what's called an infinite loop, where
the loop will go on forever (until you manually hard-exit the program -- this is generally bad).
An infinite loop, especially one that doesn't have a print statement, can look like the
computer is "hanging." If you notice this sort of thing, place a print statement in any
while loops you have, and it will immediately become obvious what's goig on.
Loops: the for-loop
While loops are great, but they're typically meant to be used when one doesn't know in
advance how many times the loop should be executed -- perhaps you want to keep prompting a user
to re-enter a password until they pick a valid one:
![](../figures/lectureNotes05/viz4.png)
Java has an alternative to the while loop for cases when you know in advance how many times
you want the loop to execute: the for loop.
Consider this example:
![](../figures/lectureNotes05/forprint.png)
Activity 2:
Type, compile and execute the above program in the Java Visualizer.
Activity 3:
In
MyForLoopPrint.java,
change the loop conditions so that the numbers 1 through 10
are printed. Also add a print statement after the
for-loop, that prints anything.
Observe:
- We are able to print out the for-loop variable i.
- We see that the loop is executed five times.
⇒
Each time the variable i has increased its value.
Mental execution:
- When execution first reaches the for-loop, the initialization
condition is executed:
![](../figures/lectureNotes05/forprint2.png)
- Say to yourself "i is set to 0".
- Important: the initialization condition is not executed
again, unless we somehow return to the statement preceding
the for-loop.
(We'll see later how this can happen.)
- Next, we test the re-entry condition:
![](../figures/lectureNotes05/forprint3.png)
- Here, you say to yourself "Is i less than 6?"
- The answer is "yes", so we enter the loop-body and execute
what's inside.
- Execute (just once) what's inside the loop body:
![](../figures/lectureNotes05/forprint4.png)
- In this case the value of i, which is now 0,
gets printed out.
- After the loop-body has executed, we apply
the increment
![](../figures/lectureNotes05/forprint5.png)
- Say to yourself "Now i has the value 1".
- Next, we test the loop-entry condition:
![](../figures/lectureNotes05/forprint6.png)
- Here, you say to yourself "Is i less than 6?"
- It clearly is, so we enter the loop again.
- Once again, we execute the loop body:
![](../figures/lectureNotes05/forprint7.png)
- Because i has the value 1, this is
what gets printed.
- Once again, we apply the increment:
![](../figures/lectureNotes05/forprint8.png)
- Say to yourself "Now i has the value 2".
- Next, apply the entry condition ... and so on.
- Finally, after the 5-th time through, i will
get the value 6.
![](../figures/lectureNotes05/forprint9.png)
- The re-entry condition now fails, and we exit the for-loop.
- What "exit" means:
![](../figures/lectureNotes05/forprint10.png)
- Execution continues to just after the for-loop.
- In this program, we didn't have anything else, but
we could have had:
![](../figures/lectureNotes05/forprint11.png)
- In this case, you would print "MOO!" to the screen.
- Another way to understand how it works:
![](../figures/lectureNotes05/forprint12.png)
The for-loop is one of several such strange and
fascinating creatures (structures) we'll encounter in
programming. There are many ways to set up a for loop, which we'll explore more
in the homework problems and exercises, especially as we combine looping with
arrays.
1D arrays: A group-of-items variable
First, recall our "box" analogy for a variable:
- Suppose we declare and assign a value to an int
variable i
![](../figures/lectureNotes05/intexample.png)
- The variable is like a "box" that can hold one
single integer value at a time.
![](../figures/lectureNotes05/intpicture.png)
An array allows you to create a connected sequences of such boxes:
![](../figures/lectureNotes05/viz5.png)
Let's trace through that example together in the Java Visualizer
to understand how arrays are created and updated in memory.
Some items to keep in mind from above:
- You must specify the size of your array upfront. You can either do this by declaring the array and its
contents between curly braces (line 7), or specifying the size and filling the array in later (line 10).
- An array can only contain one type of item, which the compiler enforces. We used integers here, but we could
have created an array of doubles, or even an array of arrays or more complicated objects (more later!).
- Java will set an empty array (with a known size) to be full of default values. Here, for integers, that
default value was 0; for other types, they will have different default values (0.0 for double, false for
boolean, and null for strings and other objects).
- Array indicies start at 0 and you cannot index past the end of an array.
- You can get the length of an array using the length field of the array instance.
Activity 4:
Modify the code above in the Visualizer to set array2 = array1. What happens?
Keep in mind you can declare an empty array with int[] arr = {};
Arrays and for-loops
Arrays go hand-in-hand with for-loops.
![](../figures/lectureNotes05/viz6.png)
Let's trace through this code together in the Java Visualizer.
Activity 5:
Modify the code above in the Visualizer to have it print out the array elements in reverse.
Activity 6:
Modify the code above in the Visualizer to have it print out every other element.
You should remember the following template for using for loops with arrays:
- Choosing what to set i to controls if you start at the beginning or end of the list;
- Similarly, you'll want to update the conditional in the middle to define when to stop. Is it at the
end of the array, the beginning, or somewhere else?
- Finally, you can choose to increment, decrement, or do something else in the update clause at the end.
- The code in the for loop is just Java code -- you can rename i to be whatever you want (and
sometimes it even makes sense to give it a more useful variable name for clarity). Similarly, the code inside
the for loop can be any valid Java code.
Assignment and copying with arrays
When assigning any two variables of matching type with =, remember that we always just
"copy the box." This is also true for arrays, as long as we understand that in terms of what an
array "stores in the box," this is not a list of values (even though it looks like it), but is
actually a memory address of the start of the entire array.
Consider the following program:
![](../figures/lectureNotes05/viz7.png)
Let's trace this through in the Java Visualizer first, and then dive deeper on paper to understand
what is going on with memory and how arrays are stored.
Activity 7:
What happens when you try to print out your arrays with System.out.println(array1)? Try it out
in the Visualizer. Now, print out what System.out.println(array1 == array2) returns. What do you
think is going on?
Explaining the strangeness of arrays: a peek under the hood
Let's show how we would trace through the example above on paper; how does Java represent arrays in memory?
Next class:
We'll go through some more in-class exercises on debugging using the terminal and the Java Visualizer.
Assignments for next lecture:
Take a look at Homework3!