GWU

CS 1111

Introduction to Software Development

GWU Computer Science


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:

Why is looping useful in computation?




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 flow of execution for a while statement is:

  1. Evaluate the condition in parentheses, yielding true or false.
  2. If the condition is false, skip the following statements in braces.
  3. 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:

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:

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:

Mental execution:

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:

An array allows you to create a connected sequences of such boxes:

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:

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.

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:

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!