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?




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 focus on three aspects of arrays that seem to beg explanation:

  1. Why do array indices start from 0?
           ⇒ That is, why start with A[0] and not A[1]?

  2. How come when one array variable is assigned to another, both seem to affect the same contents?

  3. What are those strange things printed out when we have
      // Something strange:
      System.out.println (array1);
        
To understand why, we're going dig a little deeper: Next, let's consider what happens when
        int[] A = {25, 36, 49, 64};
        int[] B;
        B = A;
        System.out.println (B[0]);
    
gets executed. Next, consider what happens next:

        int[] A = {25, 36, 49, 64};
        int[] B;
        B = A;
        System.out.println (B[0]);
        B[3] = 16;
        System.out.println (A[3]);
    
Lastly, what was that strange output we saw when we executed
  // Something strange:
  System.out.println (A);
    




Keep in mind you can declare an empty array with int[] arr = {};




When things go wrong

Which of the following have errors (syntax or bugs) and what are they? Can you tell just by reading? Don't pay attention to the purpose - just whether the program will compile or run.

Activity 10:

Activity 11:

Activity 12:

Next class:

We'll go through some more in-class exercises on debugging using the terminal and the Java Visualizer.

Assignments for next lecture:

For extra credit, post your buggy code for anything we've worked on in class so far. If it gets selected during the next class, you'll receive the extra credit!