Computer Science 112:

Introduction to Computer Science II

Gregory M. Kapfhammer

flickr photo shared by Billboard Art Project under a Creative Commons ( BY-NC-ND ) license

Color Scheme

Key Concept

Corresponding Diagram

In-Class Discussion

In-Class Activity

Details in the Textbook

What is an Array?

Motivation for Using Arrays

Important Details

An array stores a list of values

The number corresponding to each position is the index

An array of size N is indexed from 0 to N-1

Why do we start the index at the value of 0?

Array Bounds Checking

Ensures that the index is within the array

Why is this important to perform?

Let's avoid buffer overflow attacks!

Also, enables the detection of program defects

Can this be fully done at compile time?

What are the associated overheads?

Array Details

How do we declare an array?

int[] grades; and int grades[]; are both acceptable

Be consistent when you are implementing your programs!

How do we initialize an array to specific values?

int[] scores = {87, 98, 60, 80};

Arrays as Parameters

What method always accepts an array as a parameter?

An array as a parameter can be modified

You can change the contents of the array

You cannot make the array refer to another array

Command-Line Arguments

Are there other ways to give a program input?

Yes! You can input command-line arguments.

Did you ever notice that main has a parameter?

What is the purpose of String[] args?

Let's try an example!

Compile and run the program

Run this program multiple times

What is the output of this program?

Why does the output of the program vary?


What is the meaning of? ...

private int board[][] = new int[3][3];

board[0][0] + board[0][1] + board[0][2]

String[] outcome = {"O wins", "Tie", "X wins"};

What is the output of this program?


What is the purpose of this class?

What is the meaning of? ...

protected char[] encoder = new char[26];

encoder[k] = (char) ('A' + (k + rotation) % 26

for (int k=0; < msg.length; k++)

if (Character.isUpperCase(msg[k]))

msg[k] = code[j];

What is the output of this program?

Any questions about arrays?