GWU

CS 1111

Introduction to Software Development

GWU Computer Science


Lecture Notes 13: More about 1-D Arrays


Objectives




Before Starting

If you do not have your Codio course ready, use any text editor or simple IDE. Some possibilities are:




Catching Up

Before we move forward, let's catch up (complete any remaining work from the previous module)
In this case, make sure we've got:

  1. One-Dimensional Arrays... Declaring, Initializing, and Accessing!




More examples

Example 1: let's write a program to "rotate" an array:

Activity 2: Trace through the above example (RotateExample2.java) by hand to see how it works. Then, also trace through the version below and explain why it does not work:



Reversing!

Next, in the second example, we'll write code to reverse an array:

Here's a version that uses an additional array:

Activity 3: Trace through the program above by hand!! (use a table!).

Activity 4: Write code in MyReverseExample.java to achieve reversal in the same array A, without using an extra array like B.

Adding!

Example 3: adding two arrays

Activity 5: Trace through the program above (use a table!).

Activity 6: Write a different version (in AdditionExample2.java) that takes an array A and computes the following sum of two arrays, element by element, as in the above example. However, in this case, you are to compute the sum (element-by-element) of the array A and its reversal, putting the result into array B. Do this without using a third array.

Activity 7: Trace through the program below by hand.

What does it print?

Activity 8: Trace through the program below by hand.

What does it print?

Activity 9: Trace through the program below by hand.

What does it print?

Look up the definition of factorial somewhere and relate that to the computation above. Note: in the exercise above, we learned a few new things about using arrays:




Reading and writing

Let's look at an example and how to read the code:

Writing:

Using the array's built-in length. Consider this variation:

Variable names:




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:

Activity 13: The following program has multiple errors. See if you can spot them by reading. Then in ErrorExample4.java fix the errors by editing the program. The array A needs to be an array of double's.