Chapter7 - Arrays (Programming I)
Chapter7 - Arrays (Programming I)
Arrays
STIA1014 : Introduction To
Programming
Lecture Outlines
• Motivations
• Array of Primitive Data Types
• Array of Objects
• Two-dimensional Arrays
• Multi-dimensional Arrays
Learning Objectives
• To manipulate a collection of data values, using
an array.
• To declare and use an array of primitive data
types in writing a program.
• To apply array of objects in developing a
program
• To apply the principles of arrays in linear search
(sequential search)
• To manipulate data in a two-dimensional array.
• To manipulate multidimensional arrays.
Why do need Arrays?
• Let consider the following problem
item0 = read.nextInt();
item1 = read.nextInt();
item2 = read.nextInt();
item3 = read.nextInt();
item4 = read.nextInt();
sum = item0 + item1 + item2 + item3 + item4;
• We need an ARRAY.
Array Basics
• An array is a collection of data values.
• If your program needs to deal with 100
integers, 500 Account objects, 365 real
numbers, etc., you will use an array.
• In Java, an array is an indexed collection of
data values of the same type.
• Types of Arrays:
- one-dimensional array
- two-dimensional array
- multidimensional array
Array of Primitive Data Types
• Array Declaration
• Example
Variation 1 Variation 2
double[ ] rainfall; double rainfall [ ];
rainfall rainfall
= new double[12]; = new double[12];
Accessing Individual Elements
rainfall
0 1 2 3 4 5 6 7 8 9 10 11
This
Thisindexed
indexedexpression
expression
refers
refers to the elementatat
to the element
The index of the first rainfall[2] position
position#2
#2
position in an array is 0.
Array Initialization
• Like other data types, it is possible to declare and
initialize an array at the same time.
int[] number = { 2, 4, 6, 8 };
number.length 4
samplingData.length 9
monthName.length 12
Variable-size Declaration
• In Java, we are not limited to fixed-size array
declaration.
• The following code prompts the user for the size
of an array and declares an array of designated
size:
Scanner console = new Scanner(System.in);
int size;
int[] number;
element
index
sum = 0;
for(index = 0; index < sales.length;index++)
sum = sum + sales[index];
if (sales.length != 0)
average = sum / sales.length;
else
average = 0.0;
Loops and Arrays
maxIndex = sales[0];
for(index = 1; index<sales.length;index++)
if (sales[maxIndex] < sales[index])
maxIndex = index;
largestSale = sales[maxIndex];
Loops and Arrays
Suppose the array sales is as figure 9.5
Array Index Out of Bounds
• An array is in bounds if:
i. ArrayIndexOutOfBoundsException exception is
thrown.
ii. The program will terminates with an appropriate
error message
Array Index Out of Bounds
Consider the following declaration:
• Searching a value
• Calculation
• Reverse element
Searching A Value
• Eg.- A method to search an array of integer
• The Search method return the location of
the first array element equal to the search value
int Search (int[ ] num, int search
value){
int location;
for (i=0; i =num.length; i++)
if(num[i] = = search Value)
location = i;
return location;
}
Searching A Value
• Assume the num values as below:
int[] num = {10,20,30,40,50,60,70,80,90,100}
num[0] 10
num[1] 20
• If searchValue is 60, the num[2] 30
num[3] 40
method will return 5 to Search
num[4] 50
method. num[5] 60
Location, i num[6] 70
num[7] 80
num[8] 90
num[9] 100
Calculation in Array
List of parameter
The above method has 3 parameters – listA,
listB and num
Passing Arrays to Methods
Suppose we have the following statement
list of argument
Passing Arrays to Methods
public class passingParameter {
public static void main(String[] args){
int num[] = {10,20,30,40,50,60,70};
System.out.println(“ The number of elements: " + num.length);
printArray(num);
}
Passing parameter
public static void printArray(int[] number){
for (int index = 0; index < number.length; index++)
System.out.println(number[index] + ""); OUTPUT:
}
} The number of
elements: 7
10
20
30
40
50
60
Passing Arrays to Methods
continue
Passing Arrays to Methods
public static int sumArray(int[] list, int noOfElements)
{
int index;
int sum = 0;
for (index = 0; index < noOfElement; index++)
sum = sum + list[index];
return sum;
}
At A
A before searchMinimum
A.
A.Local
Localvariable
variable
number
numberdoes
does not
not
arrayOne exist before the
exist before the
method
methodexecution
execution
State of
Memory
Passing Arrays to Methods –
Status of Memory
Step 2
While at C
C inside the method
C.
C.The
Thearray
arrayisis
arrayOne number accessed
accessedvia
via
number inside
number inside
State of the
themethod.
method.
Memory
Passing Arrays to Methods –
Step 4 Status of Memory
public int searchMinimum(float[]
number))
minOne {
= searchMinimum(arrayOne);
…
D
D
}
At D
D after searchMinimum
arrayOne number
D.
D.The
Theparameter
parameterisis
erased.
erased.TheTheargument
argument
still
still points to thesame
points to the same
object.
object.
State of
Memory
Array of Strings Objects
String[] nameList = new String[5]
nameList[0] = “Amanda Green”;
nameList[1] = “Vijay Arora”;
nameList[2] = “Sheila Mann”;
nameList[3] = “Rohit Sharma”;
nameList[4] = “Mandy Johnson”;
Arrays of Objects
person
State
of
Memory
After A
A is executed
Creating an Object Array
Code Person[ ] person; Now
Nowthe
thearray
arrayfor
forstoring
storing
20 Person objects is
20 Person objects is
B
B person = new Person[20]; created,
created,but
butthe
thePerson
Person
objects
objects themselvesare
themselves are
person[0] = new Person( );
not yet created.
not yet created.
person
0 1 2 3 4 16 17 18 19
State
of
Memory
After B
B is executed
Creating an Object Array
Code Person[ ] person; One
OnePerson
Personobject
objectisis
person = new Person[20]; created
createdand
andthe
thereference
reference
totothis
this object is placedinin
object is placed
C
C person[0] = new Person( ); position
position0.0.
person
0 1 2 3 4 16 17 18 19
State
of Person
Memory
After C
C is executed
Creating an Object Array
person After D
D is executed
0 1 2 3 4 16 17 18 19
State
of
Person
Person
Person
Person
Person
Person
Person
Person
Person
Memory
Arrays of Objects – Sample 1
public class Rectangle
{
private int length,width,area;
} // end class
Arrays of Objects – Sample 1
import java.util.Scanner;
public class TestRectangle{
public static void main (String []args)
{
Scanner console = new Scanner(System.in);
Rectangle Rect[]=new Rectangle[2];
for (int j=0;j<Rect.length;j++){
System.out.print("Length : ");
int length = console.nextInt();
System.out.print("Width: ");
int width = console.nextInt();
Rect[j]=new Rectangle(length,width);
Rect[j].calculateArea();
System.out.println("Area of Rectangle " + (j+1) + " = " +
Rect[j].getArea());
System.out.println();
}
}
}//end class
Arrays of Objects – Sample 2
class Person {
private String name;
private int age;
private char gender;
public PersonList(){
person = new Person[1];
person[0] = new Person();
}
Output:
Nama =Latte
Age = 21
Gender = L
Process Exit...
Arrays of Objects – Sample 2
import java.util.*;
import java.lang.*;
class PersonList{
private Person [] person;
static Scanner read = new Scanner(System.in);
public PersonList(){
person = new Person[2];
}
public void addRecord() {
String name = null, sex=null;
int age;
char gender;
System.out.println("\n");
for (int i= 0; i< person.length; i++) {
System.out.print("\nEnter name = ");
name = read.next();
System.out.print("Enter age = ");
age = read.nextInt();
System.out.print("Enter gender = ");
sex = read.next();
gender = sex.charAt(0);
person[i] = new Person(name,age,gender);
}
}
Arrays of Objects – Sample 2
Output:
Enter name = MuthuSamy a/l Acaphan
Enter age = 23
Enter gender = male
Delete
DeletePerson
PersonBBby
A
A int delIdx = 1; setting
by
setting the referenceinin
the reference
person[delIdx] = null; position
position11totonull.
null.
person person
0 1 2 3 0 1 2 3
AA BB CC DD AA CC DD
Before A
A is executed After A
A is executed
Arrays of Objects – Sample 2
Object Deletion – Approach 2
A
A int delIdx = 1, last = 3; Delete
DeletePerson
setting
PersonBBby by
person[delIndex] = person[last]; setting the referenceinin
the reference
position
position11totothe
thelast
last
person[last] = null; person.
person.
person person
0 1 2 3 0 1 2 3
AA BB CC DD AA DD CC
Before A
A is executed After A
A is executed
Arrays of Objects – Sample 2
• Searching for a particular person. Approach 2 Deletion is used.
int i = 0;
if ( person[i] == null ) {
//not found - unsuccessful search
System.out.println("Ms. Latte was not in the array");
} else {
//found - successful search
System.out.println("Found Ms. Latte at position " + i);
}
Two-dimensional Arrays
• Two-dimensional arrays are useful in representing tabular
information.
Two-dimensional Arrays
Declaration a two-dimensional arrays
<data type> [][] <variable> //variation 1
<data type> <variable>[][] //variation 2
Example payScaleTable
0 1 2 3 4
double[][] payScaleTable; 0
payScaleTable 1
= new double[4][5];
2
3
Two-dimensional Arrays
• An element in a two-dimensional array is
accessed by its row and column index.
Two-dimensional Arrays
• Find the average of each row.
double[ ] average = { 0.0, 0.0, 0.0, 0.0 };
average[i] += payScaleTable[i][j];
}
int row;
int column;
matrix
Two-dimensional Arrays
Print
for (row = 0; row < matrix.length; row++)
{
for ( col = 0; col < matrix[row].length; col++)
System.out.println(matrix[row][col]);
System.out.println();
}
Read Data
for (row = 0; row < matrix.length; row++)
for (col = 0; col < matrix[row].length; col++)
matrix[row][col] = console.nextInt();
Two-dimensional Arrays
Sum by Row
for (row = 0; row < matrix.length; row++)
{
sum = 0;
for (col = 0; col < matrix[row].length; col++)
sum = sum + matrix[row][col];
System.out.println(“Sum of row” + (row + 1) + “ = “+ sum);
}
Sum by Column
Q & A Session