0% found this document useful (0 votes)
45 views

Chapter7 - Arrays (Programming I)

Arrays allow us to store and manipulate multiple values of the same type. They improve efficiency over declaring individual variables when dealing with large collections of data. Arrays have a length property that equals their size. We can initialize, access, and process array elements using indexes from 0 to length-1. Loops are commonly used to iterate through arrays to initialize values, input/output elements, calculate properties like sums and averages, or find maximum/minimum values.

Uploaded by

Aziemah Haidah
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

Chapter7 - Arrays (Programming I)

Arrays allow us to store and manipulate multiple values of the same type. They improve efficiency over declaring individual variables when dealing with large collections of data. Arrays have a length property that equals their size. We can initialize, access, and process array elements using indexes from 0 to length-1. Loops are commonly used to iterate through arrays to initialize values, input/output elements, calculate properties like sums and averages, or find maximum/minimum values.

Uploaded by

Aziemah Haidah
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 79

Chapter 7

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

How do we write Java program that read five


numbers, find the sum, and prints the numbers
in reverse order

• Normally, we need to store all the numbers in 5


variables before we can print it in reverse order

• Let see the following code. (next slide).


Why do need Arrays?
import java.util.Scanner;
public class ReverseOrder
{
public static void main(String [] args)
{
int item0, item1, item2, item3, item4;
int sum;
Scanner read = new Scanner (System.in);

System.out.println("Enter five integers one number per line");

item0 = read.nextInt();
item1 = read.nextInt();
item2 = read.nextInt();
item3 = read.nextInt();
item4 = read.nextInt();
sum = item0 + item1 + item2 + item3 + item4;

System.out.println("The sum of the numbers = " + sum);


System.out.println("The numbers in reverse order are: ");
System.out.println(item4 + " " + item3 + " " + item2 + " " + item1 +
" " + item0);
}
}
Why do need Arrays?
• We need 5 variables to hold the data

• What happen if we want to read 100 (or more)


numbers and print them in reverse order.

• So, we need 100 variables to hold all data.


(item0, item1, item2, item3, item4, item5,…
100)

• For large of data, this code is not desirable.

• 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

<data type> [ ] <variable> //variation 1


<data type> <variable>[ ] //variation 2
• Array Creation
<variable> = new <data type> [ <size> ]

• Example

Variation 1 Variation 2
double[ ] rainfall; double rainfall [ ];
rainfall rainfall
= new double[12]; = new double[12];
Accessing Individual Elements

• Individual elements in an array accessed with the indexed


expression.

double[] rainfall = new double[12];

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 };

double[] samplingData = { 2.443, 8.99, 12.3, 45.009, 18.2,


9.00, 3.123, 22.084, 18.08 };

String[] monthName = { "January", "February", "March",


"April", "May", "June", "July",
"August", "September", "October",
"November", "December" };

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;

System.out.print(“Size of an array = ")


size= console.nextInt());
number = new int[size];
Arrays - Example
int[] num = new int[5]; or
int num[] = new int[5];

• This statement declare and


num
creates the
array num of 5
components.
• Each component is int data
type
• The components are num[0],
num[1], num[2], num[3],
num[4]
• The value in square bracket [ ]
is call index and it start at 0
Arrays - Example

element
index

In java, [ ] is call as array subscripting operator


Items in an array is called elements
Arrays - Example
Array of five integers Array of five
called test characters called
grade

test[0] = 85; grade[0] = ‘B’;


test[1] = 98; grade[1] = ‘C’;
test[2] = 75; grade[2] = ‘B’;
test[3] = 87; grade[3] = ‘A’;
test[4] = 68; grade[4] = ‘C’;
Arrays and Instance Variable
length
• A public instance variable length is associated with each
array that has been instantiated.
• The variable length contains the size of the array.
• The variable length can be directly accessed in a
program using the array name and the dot operator.

int[] list = {10, 20, 30, 40, 50, 60};

•This statement creates the array list of six


components and initializes the components using the
values given.
• Here list.length is 6.
Loops and Arrays

• Loops can be used to process array in several


ways:
1. Initializing an array to a specific value
2. Assigning data to an array
3. Display array elements
4. Find the sum and average of an array
5. Find the largest element in the array
Loops and Arrays

1. Initializing an array to a specific value. E.g.


- to initialize every component of the array sale
with a value of 10.00

double[] sales = new double[10];


int index;

for (index = 0; index < sales.length;index++)


sales[index] = 10.00;
Loops and Arrays
2. Assigning data to an array (input from the user)
double[] sales = new double[10];
int index;

for (index = 0; index < sales.length;index++)


sales[index] = console.nextDouble();

3. Display array elements

double[] sales = new double[10];


int index;

for(index = 0; index < sales.length;index++)


System.out.print(sales[index] + " ");
Loops and Arrays
4. Find the sum and average of an array

double[] sales = new double[10];


int index, sum;
double average;

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

5. Find the largest element in the array

double[] sales = new double[10];


int index, maxIndex;
double largestSale;

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:

0 <= index <= arraySize – 1

• An array is in out bounds if:

index < 0 or index > arraySize

If an array is out of bounds;

i. ArrayIndexOutOfBoundsException exception is
thrown.
ii. The program will terminates with an appropriate
error message
Array Index Out of Bounds
Consider the following declaration:

double[] num = double[10];


int i;

• The component num[i] is valid if i = 0, 1, 2….9


• When i < 0 or i >= 10, the component num[i] is
invalid (the index is out of bounds)
Array Index Out of Bounds
list[0] 5
Consider the following loops 5
list[1]
for (i = 0; i <= 10; i++)
list[2] 5
list[i] = 5;
list[3] 5
• When i = 10; list[i] = list[10] = 5; list[4] 5
• The program tries to access list[10] list[5] 5
but does not exist
list[6] 5
• We say the index is out of bound list[7] 5
list[8] 5
list[9] 5
Array Processing – Sample 1
Scanner console = new Scanner(System.in);
double[] rainfall = new double[12];
double annualAverage,
sum = 0.0;

for (int i = 0; i < rainfall.length; i++) {

System.out.print(“Rainfall for month “+(i+1)+” =“);


rainfall[i] = console.nextDouble();
sum += rainfall[i];
}
annualAverage = sum / rainfall.length;
System.out.println("Average is = "+anualAverage);
Array Processing – Output
Rainfall for month 1=100.00
Rainfall for month 2=120.00
Rainfall for month 3=200.00
Rainfall for month 4=200.00
Rainfall for month 5=300.00
Rainfall for month 6=150.00
Rainfall for month 7=100.00
Rainfall for month 8=145.00
Rainfall for month 9=125.00
Rainfall for month 10=200.00
Rainfall for month 11=200.00
Rainfall for month 12=300.00
Average is = 178.33
Press any key to continue...
Array Processing – Sample 2
Scanner console = new Scanner(System.in);
double[] rainfall = new double[2];
String[] monthName = new String[2];
monthName[0] = "January";
monthName[1] = "February";

double annualAverage, sum = 0.0;

for (int i = 0; i < rainfall.length; i++) {


System.out.print(“Rainfall for month “+monthName[i]+” =“)
rainfall[i] = console.nextDouble();
sum += rainfall[i];
}
annualAverage = sum / rainfall.length;
System.out.println("Average is = "+anualAverage);
Array Processing – Output

Rainfall for January=150.00


Rainfall for February=250.00
Average is = 200.00
Press any key to continue...
Array Processing – Sample 3
• Compute the average rainfall for each quarter.

//assume rainfall is declared and initialized properly

double[] quarterAverage = new double[4];

for (int i = 0; i < 4; i++) {


sum = 0;
for (int j = 0; j < 3; j++) {
//compute the sum of
sum += rainfall[3*i + j]; //one quarter
}
quarterAverage[i] = sum / 3.0; //Quarter (i+1) average
}
Manipulate Data in Arrays

• 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

• Eg:- add a number from Array1 and Array2,


and store the total in Array3
• Assume Array1, Array2 and Array3 declarations
as below:
int[ ] Array1 = {10,20,30,40,50,60,70,80,90,100};
int[ ] Array2 = {11,22,33,44,55,66,77,88,99,110};
int[ ] Array3 = new int[10];
Calculation in Array
Array[0] 10 Array[0] 11 Array[0] 21
Array[1] 20 Array[1] 22 Array[1] 42
Array[2] 30 Array[2] 33 Array[2] 63
Array[3] 40 Array[3] 44 Array[3] 84
Array[4] 50 Array[4] 55 Array[4] :
Array[5] 60
+ Array[5] 66 Array[5] :
Array[6] 70 Array[6] 77 Array[6] :
Array[7] 80 Array[7] 88 Array[7] :
Array[8] 90 Array[8] 99 Array[8] :
Array[9] 100 Array[9] 110 Array[9] :
Calculation in Array
int[] Array1 = {10,20,30,40,50,60,70,80,90,100};
int[] Array2 = {11,22,33,44,55,66,77,88,99,110};
int[] Array3 = new int[10];
int i;
Output

for (i=0; i < 10; i++) Array3[0] = 21


{ Array3[1] = 42
Array3[i] = Array1[i] + Array2[i];
Array3[2] = 63
System.out.println("Array3["+i+"]=“ Array3[3] = 84
+Array3[i]);
Array3[4] = 105
}
Array3[5] = 126
Array3[6] = 147
Array3[7] = 168
Array3[8] = 189
Array3[9] = 210
Calculation in Array
for (i=0; i < 10; i++)
Array3[i] = Array1[i] + Array2[i];

Values of Array3 during for loop iterations


i Array1[i] Array2[i] Array3[i]
0 10 11 21
1 20 22 42
2 30 33 63
3 40 44 84
4 50 55 105
5 60 66 126
6 70 77 147
7 80 88 168
8 90 99 189
9 100 110 210
Reverse Array Elements
Eg- Read 10 integer numbers, and print the
numbers in reverse order

Scanner console = new Scanner (System.in);


int item[] = new int[10];
int i;
//Read integers number and store in item[i]
System.out.println("Enter ten integers number:");
for(i = 0; i < 10; i++)
item[i] = console.nextInt();

//Print the output in reverse order are:");


System.out.println("The numbers in reverse order are:");
for(i = 9; i >= 0; i--)
System.out.println(item[i]);
Enter ten integers number:
Output 56
65
67
43
64
76
39
77
47
84
The numbers in reverse order are:
84
47
77
39
76
64
43
67
65
56
Passing Arrays to Methods

Arrays can be passed as parameter to methods


Eg.
public void arrayAsFormalParameter(int[] listA,
double[] listB, int num)
{
//…
}

List of parameter
The above method has 3 parameters – listA,
listB and num
Passing Arrays to Methods
Suppose we have the following statement

int[] intList = new int[10];


double[] doubleNumList = new double[15];
int number;

Statement to call the method

arrayAsFormalParameter(intList, doubleNumList, number);

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

public static void main(String[] args){


int[] listA = {11,22,36,42,15,46,27,48,19,10}
int[] listB = new int[10];
int Total, Largest;

// call sumArray method and return a value to Total

Total = sumArray (listA, listA.length);


System.out.println(“\n The sum of ListA is :” + Total);

// call indexLargestElement and return the indux value to Largest

indLargest = indexLargestElement (listA, list.length);


System.out.println(“\n The largest element is :” + listA[Largest]);

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;
}

public static int indexLargestElement(int[] list, int noOfElement)


{
int index;
int maxIndex = 0;
for (index = 1; index < noOfElement; index++)
if(list[maxIndex] < list[index])
maxIndex = index;
return maxIndex;
}
Passing Arrays to Methods –
Code Status of Memory
Step 1
A
A
minOne public int searchMinimum(float[]
= searchMinimum(arrayOne); number))
{

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

public int searchMinimum(float[] number))


{
minOne B
B
= searchMinimum(arrayOne); …
}

The address is copied at B


B B.
B.The
Thevalue
valueofofthe
the
argument,
argument,which
whichisis
an
anaddress,
address,isis
arrayOne number copied
copiedtotothe
the
parameter.
parameter.
State of
Memory
Passing Arrays to Methods –
Status of Memory
Step 3
public int searchMinimum(float[]
number))
{
minOne C
C
= searchMinimum(arrayOne);
}

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

• In Java, in addition to create arrays of


primitive data types (int, double, float, char etc),
we can declare arrays of objects
• An array of primitive data is a powerful tool,
but an array of objects is even more powerful.
• The use of an array of objects allows us to
model the application more cleanly and
logically.
Declaring an Object Array
Code A
A Person[ ] person;
Only
Onlythe
thename
nameperson
person
person = new Person[20];
isisdeclared,
declared, no arrayisis
no array
person[0] = new Person( ); allocated
allocatedyet.
yet.

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

Code for(int i=0;i<Person.length;i++)


20
20Person
Personobjects
objectsare
are
created and the
created and the
D
D person[i] = new Person( ); references
referencestotothese
these
objects
objects are placedin
are placed in
position 0 to 19.
position 0 to 19.

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;

public Rectangle (int l, int w){


length = l;
width = w;
}

public void calculateArea() {


area = length * width;
}

public int getArea() {


return 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 Person(String newName, int newAge, char newGender){


name = newName;
age = newAge;
gender = newGender;
}

public void setName(String newName){


name = newName;
}
Arrays of Objects – Sample 2
public void setAge(int newAge){
age = newAge;
}

public void setGender(char newGender){


gender = newGender;
}

public String getName(){


return name;
}

public int getAge(){


return age;
}

public char getGender(){


return gender;
}
Arrays of Objects – Sample 2
class PersonList
{
private Person [] person;

public PersonList(){
person = new Person[1];
person[0] = new Person();
}

public void addRecord(){


person[0].setName("Latte");
person[0].setAge(21);
person[0].setGender('L');
}
Arrays of Objects – Sample 2

public void displayRecord(){


System.out.println("\n\nNama =
"+person[0].getName());
System.out.println("Age = "+person[0].getAge());
System.out.println("Gender =
"+person[0].getGender());
}

public static void main(String[] arg)


{
PersonList list1 = new PersonList();
list1.addRecord();
list1.displayRecord();
}
} // end class PersonList
Arrays of Objects – Sample 2

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

public void displayRecord()


{
for (int i= 0; i< person.length; i++)
{
System.out.println("\n\nNama =
"+person[i].getName());
System.out.println("Age = "+person[i].getAge());
System.out.println("Gender =
"+person[i].getGender());
}
}

public static void main(String[] arg) throws IOException


{
PersonOperation_2 people = new PersonOperation_2();
people.addRecord();
people.displayRecord();
}
} // end ersonOperation_2
Arrays of Objects – Sample 2

Output:
Enter name = MuthuSamy a/l Acaphan
Enter age = 23
Enter gender = male

Enter name = Siti Sarah binti Zakaria


Enter age = 19
Enter gender = female

Nama = MuthuSamy a/l Acaphan Age = 23 Gender =m


Nama = Siti Sarah binti Zakaria Age = 19 Gender =f
Process Exit...
Arrays of Objects – Sample 2
• Find the youngest and oldest persons.
int minIdx = 0; //index to the youngest person
int maxIdx = 0; //index to the oldest person

for (int i = 1; i < person.length; i++) {

if ( person[i].getAge() < person[minIdx].getAge() ) {


minIdx = i; //found a younger person

} else if (person[i].getAge() > person[maxIdx].getAge() ) {

maxIdx = i; //found an older person


}
}

//person[minIdx] is the youngest and person[maxIdx] is the oldest


Arrays of Objects – Sample 2
Object Deletion – Approach 1

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;

while ( person[i] != null && !person[i].getName().equals("Latte") ) {


i++;
}

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

Creation a two-dimensional arrays


<variable> = new <data type> [intRow][intColumn ]

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 };

for (int i = 0; i < payScaleTable.length; i++) {

for (int j = 0; j < payScaleTable[i].length; j++) {

average[i] += payScaleTable[i][j];
}

average[i] = average[i] / payScaleTable[i].length;


}
Two-dimensional Arrays
• E.g.
• Initialization
• Print
• Input data/store data into 2-Dimensional array
• Sum the data
• Find the largest element
• Suppose the declaration as below:

int row;

int column;

int matix = new int[7][6];


Two-dimensional Arrays
Initialization
for (row = 0; row < matrix.length; row++)
for (col = 0; col < matrix[row].length; col++)
matrix[row][col] = 10;

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

for (col = 0; col < matrix[0].length; col++)


{
sum = 0;
for (row = 0; row < matrix.length; row++)
sum = sum + matrix[row][col];
System.out.println(“Sum of column” + (col + 1) + “=“+ sum);
}
Two-dimensional Arrays

Largest Element in Each Row

for (row = 0; row < matrix.length; row++)


{
largest = matrix[row][0];
for (col = 1; col < matrix[row].length; col++)
if (largest < matrix[row][col])
largest = matrix[row][col];
System.out.println(“The largest element of row” + (row+1)
+ “=“ + largest);
}
Multi-dimensional Arrays
• Can define three-dimensional arrays or n-dimensional
arrays (n can be any number).
• Syntax to declare and instantiate array:
dataType[][]…[] arrayName = new
dataType[intExp1][intExp2]…[intExpn];

• Syntax to access component:


arrayName[indexExp1][indexExp2]…[indexExpn]
• intExp1, intExp2, ..., intExpn = positive integers
• indexExp1,indexExp2, ..., indexExpn = non-negative
integers
Multi-dimensional Arrays
double[][][] carDealers = new double[10][5][7];

for (i = 0; i < 10; i++)


for (j = 0; j < 5; j++)
for (k = 0; k < 7; k++)
carDealers[i][j][k] = 10.00;
Conclusion

Q & A Session

You might also like