Fundamentals of Software
Development
CT010-3-1
Introduction to collections of data
and associated operations: Arrays
Prepared by: SZK First Prepared on:30 th July 2005 Last Modified on:14th December 2005
Quality checked by: GTK
Copyright 2005 Asia Pacific University College of Technology and Innovation
Topic & Structure of the lesson
Introduction to collections of data and
associated operations:
Array basics
Simple Array processing Loops
One-Dimensional Arrays
Examples of Array Programs
CT010-3-1 Fundamentals of Software Development
Arrays
Learning Outcomes
At the end of this topic, you should be able to:
Define, initialise and access array data types
Create, edit, compile, run and debug simple
procedural - based Java programs using arrays
CT010-3-1 Fundamentals of Software Development
Arrays
Key Terms
If you have mastered this topic, you should be able to
use the following terms correctly in your assignments
and exams:
Array data types
CT010-3-1 Fundamentals of Software Development
Arrays
Array Basics
Definition
An array contains a fixed number (called its length) of
variables of identical type.
In Java, it is a specialized kind of object and it must be
declared in 2 steps :
1. Declare the object :
type[] array_name;
Eg.
CT010-3-1 Fundamentals of Software Development
int[] counts;
double[] scores;
Time[] appointmentTime;
Arrays
Array Basics
2. Allocate the object :
array_name = new type [size];
Eg.
counts= new int[10];
scores= new double[15];
appointmentTime = new Time[10];
Combination of 2 steps :
type [] array_name = new type [size];
Eg.
CT010-3-1 Fundamentals of Software Development
int counts= new int[10];
Arrays
Array Basics
The bracketed no. is the length (which states how many
variables in each array.
0 1 2 3 4 5 6 7 8 9 } index /
subscript
counts
int variables
Arrays can contain any type of value : simple values or
references to objects
To obtain a specific variable, we use subscripts, for eg.
CT010-3-1 Fundamentals of Software Development
Arrays
Array Basics
counts[0]
// the first variable in counts
counts[1]
// the second variable in counts
counts[9]
// the last variable in counts
counts[10]
// error :
ArrayIndexOutOfBounds
Each of these subscripted arrays is an int variable and can
be used in the same ways that any int variable is used.
CT010-3-1 Fundamentals of Software Development
Arrays
Array Basics
Example 1 :
Write and run a program that read 10 integers and print
it in reverse order.
class Simple {
public static void main (String[] arg) {
int[] counts = new int[10];
System.out.print("Enter ten numbers: ");
counts[0]=Keyboard.readInt();
counts[1]=Keyboard.readInt();
counts[2]=Keyboard.readInt();
counts[3]=Keyboard.readInt();
counts[4]=Keyboard.readInt();
counts[5]=Keyboard.readInt();
counts[6]=Keyboard.readInt();
counts[7]=Keyboard.readInt();
counts[8]=Keyboard.readInt();
counts[9]=Keyboard.readInt();
Sample program :
CT010-3-1 Fundamentals of Software Development
System.out.print(counts[9] + " " + counts[8] + " "
+ counts[7] + " " + counts[6] + " "
+ counts[5] + " " + counts[4] + " "
+ counts[3] + " " + counts[2] + " "
+ counts[1] + " " + counts[0] + "\n");
}
Arrays
Array Basics
Sample program:
class Simple {
public static void main (String[] arg) {
int[] counts = new int[10];
System.out.print("Enter ten numbers: ");
counts[0]=Keyboard.readInt();
counts[1]=Keyboard.readInt();
counts[2]=Keyboard.readInt();
counts[3]=Keyboard.readInt();
counts[4]=Keyboard.readInt();
counts[5]=Keyboard.readInt();
counts[6]=Keyboard.readInt();
counts[7]=Keyboard.readInt();
counts[8]=Keyboard.readInt();
counts[9]=Keyboard.readInt();
System.out.print(counts[9] + " " + counts[8] + " " + counts[7] + " " +
counts[6] + " " + counts[5] + " " + counts[4] + " " + counts[3] + " " +
counts[2] + " " + counts[1] + " " + counts[0] + "\n");
}
CT010-3-1 Fundamentals of Software Development
Arrays
Array Basics
Array Features To Be Noted:
Array subscripts can be expression, not just constant.
Eg.
counts[1]
// constant array subcript
}
counts[i]
array subcript in expression
counts[i*2]
form
counts[i/2]
CT010-3-1 Fundamentals of Software Development
Arrays
Array Basics
Arrays can be initialized by giving a list of all their
elements :
int[] primes = { 2,3,5,9,11,13,17,19,23,29 };
However, this can only be used at the time the array is
declared. Thus,
int[] prime;
primes = { 2,3,5,9,11,13,17,19,23,29 };
CT010-3-1 Fundamentals of Software Development
Arrays
} ILLEGAL
Array Basics
Array Features To Be Noted (contd) :
The above method can also be used to initialized an array of
Strings such as :
final String NAME[] = { ; Sunday; Monday,
Tuesday, Wednesday, Thursday, Friday,
Saturday);
int day=1;
void printName (int day) {
while (day <=7) {
System.out.print( NAME[day] );
day++;
}
}
CT010-3-1 Fundamentals of Software Development
Arrays
Array Basics
Javas array have an important instant variable : length,
which tells the no of elements in the array.
while (day <= NAME.length) {
System.out.print( NAME[day] );
day++;
}
CT010-3-1 Fundamentals of Software Development
Arrays
Simple Array Processing Loops
Now, lets use for loop to generate the subscript of an array.
for (int i=0; i<10; i++)
count[i] = i*10;
or, we can use arrays length instance variable
for (int i=0; i<count.length; i++)
count[i] = i*10;
counts
0 1
2 3 4 5 6 7 8 9
0 10 20 30 40 50 60 70 80 90
CT010-3-1 Fundamentals of Software Development
Arrays
Simple Array Processing Loops
Example 2 :
Write a more concise program for the Simple Program.
Sample program :
class Simple2 {
public static void main (String[] arg) {
int[] counts = new int[10];
System.out.print("Enter ten numbers: ");
for (int i=0; i<10; i++)
counts[i]=Keyboard.readInt();
for (int i=0; i<10; i++)
System.out.print(counts[9-i] + " ");
System.out.println();
}
}
CT010-3-1 Fundamentals of Software Development
Arrays
Modular Programming Example
Example 3 :
Encapsulate the reading & echoing of an array in a class called Collection :
Sample program :
class ReadAndEcho {
static final int INPUT_MAX = 1000;
public static void main (String[] arg) {
Collection c = new
Collection(INPUT_MAX);
c.readAndEcho();
}
}
CT010-3-1 Fundamentals of Software Development
Arrays
The Main Program
(The Client)
It can instantiate a
Collection Object,
providing a large no.
as an argument to
the constructor.
Modular Programming Example
Collection
class
class Collection {
int[] item;
int size = 0;
public Collection (int number) {
item = new int[number];
}
public void readAndEcho () {
// Input up to 'number' numbers
System.out.print("Enter first number: ");
int n = Keyboard.readInt();
while (!Keyboard.eof()) {
// The first size inputs are stored in item[0] .. item[size-1]
item[size] = n;
size++;
System.out.print("Enter next number: ");
n = Keyboard.readInt();
}
System.out.println();
// Print numbers, one per line
for (int i=0; i<size; i++)
System.out.println(item[size-i]);
CT010-3-1 Fundamentals of Software Development
Arrays
Modular Programming Example
Write a program, which reads a sequence of student names and
scores on 2 exams and prints a listing giving the average score
for each student. The input for each student is in the form of a
name (String) and 2 numbers.
Sample run of the program :
Enter name and two exam grades : Clark Kent
57
69
Enter name and two exam grades : Lois Lane
94
86
Enter name and two exam grades : Jimmy Olsen
90
97
Enter name and two exam grades : ^D or ^Z
Name
Clark Kent
Lois Lane
Jimmy Olsen
CT010-3-1 Fundamentals of Software Development
Average
Arrays
63
90
83
Modular Programming Example
Main Program
class ReadAndAvg2 {
static final int INPUT_MAX = 100;
public static void main (String[] arg)
{
GradeBook grades = new
GradeBook(INPUT_MAX);
grades.readAndAverage();
}
}
Gradebook class
class GradeBook {
String[] names;
int[] exam1, exam2;
int size = 0;
public GradeBook(int number) {
names = new String[number];
exam1 = new int[number];
exam2 = new int[number];
}
public void readAndAverage() {
// Read names and exam grades; size counts inputs
while (true) {
System.out.print("Enter name and two exam grades:
");
names[size] = Keyboard.readString();
if (Keyboard.eof()) break;
exam1[size] = Keyboard.readInt();
exam2[size] = Keyboard.readInt();
size++;
}
}
CT010-3-1 Fundamentals of Software Development
System.out.println();
System.out.println("\tName\tAverage");
for (int i=0; i<size; i++) {
System.out.println("\t" + names[i] +
"\t\t" + (exam1[i] + exam2[i])/2);
Arrays
Modular Programming Example
A better structure for GradeBook would be define a class of
objects representing students ~ including their names and grades
and construct an array of these objects.
Student class
CT010-3-1 Fundamentals of Software Development
class Student {
private String name;
private int exam1, exam2;
public Student () {}
public void setName (String s) { name =
s; }
public void setExam1 (int s) { exam1 = s; }
public void setExam2 (int s) { exam2 = s; }
public String getName () { return name; }
public int getExam1 () { return exam1; }
public int getExam2 () { return exam2; }
public int getAvg () { return
(exam1+exam2)/2; }
}
Arrays
Modular Programming Example
class GradeBook {
Student[] students; int size = 0;
Main Program
class ReadAndAvg2 {
static final int INPUT_MAX = 100;
public static void main (String[] arg)
{
GradeBook grades = new
GradeBook(INPUT_MAX);
grades.readAndAverage();
}
}
Gradebook class
CT010-3-1 Fundamentals of Software Development
public GradeBook(int number) {
students = new Student[number];
}
public void readAndAverage() {
// Read names and exam grades
String nextname;
while (true) {
System.out.print("Enter name and 2 grades: ");
nextname = Keyboard.readString();
if (Keyboard.eof()) break;
students[size] = new Student();
students[size].setName(nextname);
students[size].setExam1(Keyboard.readInt());
students[size].setExam2(Keyboard.readInt());
size++;
}
System.out.println(\n\tName\tAverage");
for (int i=0; i<size; i++) {
System.out.println("\t" + students[i].getName()
+"\t\t" + students[i].getAvg()); }
}}
Arrays
Quick Review Question
Read a sequence of numbers terminated by the end-of file
character and store them in an array A and perform the
following operations (where and is the number of
inputs):
a) Compute & print running sums in both forward and
backward directions. Specifically, compute and print
arrays B & C, where B[i]=A[0]+A[1]+...+A[i], and
C[i]=A[n-1]+A[n-2]+...+A[i].
b) Compute pairwise differences : D[i] = A[i+1]-A[i].
CT010-3-1 Fundamentals of Software Development
Arrays
Quick Review Question
c) Compute three-way averages : E[i]=(A[i]
+A[i+1]+A[i+2])/3
d) Compute the increasing values within the array. That is,
start with F[0]=A[0]. Then compute F[1] to be the value
A[i], where i is the smallest index such that A[j]>A[0].
Then compute F[2] to be the value A[j], where j is the
smallest index greater than i such that A[j]>A[i], and so
on. For example, if inputs the inputs are 5, -5, 10, 13, 4,
40, 25, 6, then F should contain the values 5, 10, 13, and
40.
CT010-3-1 Fundamentals of Software Development
Arrays
Quick Review Question
Sample execution
Enter first number : 12
Enter next number : 23
Enter next number : 56
Enter next number : 34
Enter next number : 90
Enter next number : 78
Enter next number : ^D or ^Z
i
0
1
2
3
4
5
CT010-3-1 Fundamentals of Software Development
A[i]
12
23
56
34
90
78
B[i]
12
35
91
125
215
293
C[i]
293
281
258
202
168
78
Arrays
D[i]
11
33
-22
56
-12
E[i]
30
37
60
67
F[i]
12
23
56
90
Summary of Main Teaching Points
Introduction to collections of data and
associated operations:
Array basics
Simple Array processing Loops
One-Dimensional Arrays
Examples of Array Programs
CT010-3-1 Fundamentals of Software Development
Arrays
Next Lesson
Packages
Introduction to Packages
API Packages
Using import
Sample programs
CT010-3-1 Fundamentals of Software Development
Arrays