Chapter 9: Arrays - PowerPoint PPT Presentation

1 / 70
About This Presentation
Title:

Chapter 9: Arrays

Description:

Explore how to declare and manipulate data into arrays. Understand the meaning of ' ... Can specify different number of columns for each row (ragged arrays) ... – PowerPoint PPT presentation

Number of Views:40
Avg rating:3.0/5.0
Slides: 71
Provided by: manasi61
Category:
Tags: arrays | chapter | ragged

less

Transcript and Presenter's Notes

Title: Chapter 9: Arrays


1
Chapter 9 Arrays
  • Java Programming
  • From Problem Analysis to Program Design,
  • Second Edition

2
Chapter Objectives
  • Learn about arrays.
  • Explore how to declare and manipulate data into
    arrays.
  • Understand the meaning of array index out of
    bounds.
  • Become familiar with the restrictions on array
    processing.

3
Chapter Objectives
  • Discover how to pass an array as a parameter to a
    method.
  • Discover how to manipulate data in a
    two-dimensional array.
  • Learn about multidimensional arrays.

4
Array
  • A structured data type with a fixed number of
    components.
  • Every component is of the same type.
  • Components are accessed using their relative
    positions in the array.

5
One-Dimensional Arrays
  • Syntax to instantiate an array
  • dataType arrayName
  • arrayName new dataTypeintExp
  • dataType arrayName new dataTypeintExp
  • dataType arrayName1, arrayName2
  • Syntax to access an array component
  • arrayNameindexExp
  • intExp number of components in array gt 0
  • 0 lt indexExp lt intExp

6
int num new int5
Array num
7
Array list
8
Specifying Array Size During Program Execution
  • int arraySize
  • System.out.print("Enter the size of "
  • "the array ")
  • arraySize console.nextInt()
  • System.out.println()
  • int list new intarraySize

9
Array Initialization During Declaration
  • double sales 12.25, 32.50, 16.90, 23,
  • 45.68
  • The values, called initial values, are placed
    between braces and separated by commas.
  • Here, sales0 12.25, sales1 32.50, sales2
    16.90, sales3 23.00, and sales4 45.68.
  • When declaring and initializing arrays, the size
    of the array is determined by the number of
    initial values within the braces.
  • If an array is declared and initialized
    simultaneously, we do not use the operator new to
    instantiate the array object.

10
Arrays and the 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.
  • This statement creates the array list of six
    components and initializes the components using
    the values given. Here list.length is 6.
  • int list 10, 20, 30, 40, 50, 60

11
Arrays and the Instance Variable length
  • This statement creates the array numList of 10
    components and initializes each component to 0.
  • int numList new int10
  • The value of numList.length is 10.
  • These statements store 5, 10, 15, and 20,
    respectively, in the first four components of
    numList.
  • numList0 5
  • numList1 10
  • numList2 15
  • numList3 20
  • You can store the number of filled elements, that
    is, the actual number of elements, in the array
    in a variable, say noOfElement. It is a common
    practice for a program to keep track of the
    number of filled elements in an array.

12
Processing One-Dimensional Arrays
  • Loops used to step through elements in array and
    perform operations.
  • int list new int100
  • int i
  • for (i 0 i lt list.length i)
  • //process listi, the (i 1)th
  • //element of list
  • for (i 0 i lt list.length i)
  • listi console.nextInt()
  • for (i 0 i lt list.length i)
  • System.out.print(listi " ")

13
Arrays
  • Some operations on arrays
  • Initialize
  • Input data
  • Output stored data
  • Find largest/smallest/sum/average of elements

double sales new double10 int
index double largestSale, sum, average
14
Code to Initialize Array to Specific Value (10.00)
for (index 0 index lt sales.length
index) salesindex 10.00
Code to Read Data into Array
for (index 0 index lt sales.length
index) salesindex
console.nextDouble()
Code to Print Array
for (index 0 index lt sales.length
index) System.out.print(salesindex
" ")
15
Code to Find Sum and Average of Array
sum 0 for (index 0 index lt sales.length
index) sum sum
salesindex if (sales.length ! 0) average
sum / sales.length else average 0.0
Determining Largest Element in Array
maxIndex 0 for (index 1 index lt
sales.length index) if
(salesmaxIndex lt salesindex) maxIndex
index largestSale salesmaxIndex
16
Determining Largest Element in Array
17
  • / program to create an array called cpsc,
    instantiate the array, enter some data into
  • // the array, compute the average of the data,
    and look for the largest member of the array
  • import java.util.
  • public class array1
  • public static void main (String mike)
  • Scanner console
  • console new Scanner(System.in)
  • int cpsc //create the array
  • cpsc new int10 // instantiate the array
    to contain 10 elements and value 0 each
  • // to enter new values into the array
  • int i
  • System.out.println("enter ten integer numbers
    separated by spaces")
  • for (i0 iltcpsc.lengthi)
  • cpsci console.nextInt()

18
  • // to find sum and average
  • double sum
  • double avg
  • sum0.00
  • for(i0 iltcpsc.length i)
  • sum sum cpsci
  • avg sum/cpsc.length
  • System.out.println("Sum" "" sum "and" " "
    "Average" "" avg)
  • // to find largest element of the array
  • int maxind0
  • int largestval0
  • for (i1 iltcpsc.length ii1)
  • if (cpscmaxindltcpsci)
  • maxindi
  • largestvalcpscmaxind
  • System.out.println("Largest value"largestval)

19
(No Transcript)
20
Array Index Out of Bounds
  • An array is in bounds if
  • 0 lt index lt arraySize 1
  • If index lt 0 or index gt arraySize
  • ArrayIndexOutOfBoundsException exception is
    thrown.
  • Base address Memory location of the first
    component in an array.

21
Declaring Arrays as Formal Parameters to Methods
  • General syntax to declare an array as a formal
    parameter
  • dataType arrayName
  • public static void arraysAsFormalParameter(int
    listA,
  • double listB, int num)
  • //...
  • int intList new int10
  • double doubleNumList new double15
  • int number
  • arraysAsFormalParameter(intList, doubleNumList,
    number)

22
Methods for Array Processing
  • public static void fillArray(int list,
  • int noOfElements)
  • int index
  • for (index 0 index lt noOfElements
  • index)
  • listindex console.nextInt()

23
The Assignment Operators and Arrays
24
The Assignment Operators and Arrays
25
The Assignment Operators and Arrays
  • for (int index 0 index lt listA.length
  • index)
  • listBindex listAindex

26
Relational Operators Arrays
  • if (listA listB)
  • ...
  • The expression listA listB determines if the
    values of listA and listB are the same, thus
    determining whether listA and listB refer to the
    same array.
  • To determine whether listA and listB contain the
    same elements, you need to compare them component
    by component.
  • You can write a method that returns true if two
    int arrays contain the same elements.

27
Relational Operators and Arrays
boolean isEqualArrays(int firstArray,
int secondArray) if
(firstArray.length ! secondArray.length)
return false for (int index 0 index lt
firstArray.length
index) if (firstArrayindex !
secondArrayindex) return false
return true if (isEqualArrays(listA,
listB)) ...
28
  • //to determine if the values of two arrays are
    equal
  • import java.util.
  • public class array2
  • public static boolean mike (double faith1,
    double faith2)
  • boolean anstrue
  • int j
  • if(faith1.length ! faith2.length)
  • ansfalse
  • for(j0 jltfaith1.length j)
  • if (faith1j ! faith2j)
  • ansfalse
  • else
  • anstrue
  • return ans
  • public static void main(String args)

29
  • System.out.println("enter four decimal numbers
    separated by spaces for list1")
  • for (i0 iltlist1.lengthi)
  • list1i console.nextDouble()
  • System.out.println("enter four decimal numbers
    separated by spaces for list2")
  • for (i0 iltlist2.lengthi)
  • list2i console.nextDouble()
  • // to print out the values of list1 and list2
  • int k
  • for(k0 kltlist1.length k)
  • System.out.println(list1k)
  • System.out.println()
  • for(k0 kltlist2.length k)
  • System.out.println(list2k)
  • // to print the two arrays in two columns

30
(No Transcript)
31
Arrays of Objects
  • Can use arrays to manipulate objects.
  • Example Create an array named array1 with N
    objects of type T
  • T array1 new TN
  • Can instantiate array1 as follows
  • for(int j0 j ltarray1.length j)
  • array1j new T()

32
Array of String Objects
  • String nameList new String5
  • nameList0 "Amanda Green"
  • nameList1 "Vijay Arora"
  • nameList2 "Sheila Mann"
  • nameList3 "Rohit Sharma"
  • nameList4 "Mandy Johnson"

33
Array of String Objects
  • Some String methods to work on array
  • nameList0.equals(Amanda Green) returns true
  • nameList3.substring(0,3) returns Rohi

34
Clock arrivalTimeEmp new Clock100
Arrays of Objects
35
Instantiating Array Objects
for (int j 0 j lt arrivalTimeEmp.length j)
arrivalTimeEmpj new Clock()
36
Instantiating Array Objects
arrivalTimeEmp49.setTime(8, 5, 10)
37
Parallel Arrays
  • Two (or more) arrays are said to be parallel if
    their corresponding components hold related
    information.
  • For example, we can have arrays that hold
    students ID, and another that holds GPA.
  • Each component of the array corresponds to a
    given students information

38
  • import java.util.
  • public class array3
  • public static void main(Stringme1)
  • // to read the id, and gpa and get degree class
    of 5 students
  • int numb5
  • Stringid "14562","15628", "17829","24561","25
    678"
  • double gpa 3.89,4.91,3.89,4.23,2.98
  • String dclass
  • dclassnew String5
  • int i
  • // compute the grade based on gpa
  • Upper"
  • else if (gpaigt 2.50 gpailt3.50)
    dclassi"Second Class Lower"
  • else if (gpaigt 1.50 gpailt2.50)
    dclassi"Third Class"

Program Output
39
Arrays and Variable Length Parameter List
  • We may use same name for different methods
    (polymorphism) but with different parameter
    lists.
  • Example public static int faith(int x, int y)
  • public static int
    faith(int x, int y, int z)
  • public static int
    faith (int w, int x, int y, int z)
  • We may intend that the list of parameters could
    be variable (ie be two, three, four, etc). In
    that case, the syntax to declare a variable
    length formal parameter (list) is
  • dataType ... Identifier
  • E.g. public static int faith(intnumList)
  • Where numList is a formal parameter (an array
    whose components are each integers)
  • In calling the method, we specify the actual
    parameters of type integer.

40
Arrays and Variable Length Parameter List
  • A method can also have both variable length
    formal parameter and other formal parameters
  • E.g. public static void faith(String name,
    double gpa, intnumList)
  • A method can only have one variable length formal
    parameter
  • If a method has both variable length formal
    parameter and other formal parameters, then the
    variable length formal parameter should be the
    last to be listed on the parameter list

41
Arrays and Variable Length Parameter List
  • public static double largest(double ... numList)
  • double max
  • int index
  • if (numList.length ! 0)
  • max list0
  • for (index 1 index lt numList.length
  • index)
  • if (max lt numList index)
  • max numList index
  • return max
  • return 0.0

42
Arrays and Variable Length Parameter List
  • double num1 largest(34, 56)
  • double num2 largest(12.56, 84, 92)
  • double num3 largest(98.32, 77, 64.67, 56)
  • System.out.println(largest(22.50, 67.78,
  • 92.58, 45, 34, 56))
  • double numberList 18. 50, 44, 56.23, 17.89
  • 92.34, 112.0, 77, 11, 22,
  • 86.62
  • System.out.println(largest(numberList))

43
foreach loop
  • The syntax to use this for loop to process the
    elements of an array is
  • for (dataType identifier arrayName)
  • statements
  • identifier is a variable, and the data type of
    identifier is the same as the data type of the
    array components.

44
foreach loop
  • sum 0
  • for (double num list)
  • sum sum num
  • The for statement in Line 2 is read for each num
    in list. The identifier num is initialized to
    list0. In the next iteration, the value of num
    is list1, and so on.
  • for (double num numList)
  • if (max lt num)
  • max num

45
  • // example on variable length formal parameter
    and alternative looping
  • //
  • public class array4
  • private String firstName
  • private String lastName
  • private double testScores // array to store
    test scores
  • private char grade
  • // default constructor
  • public array4()
  • firstName""
  • lastName""
  • grade ''
  • testScores new double5
  • // constructor with variable length parameter
    list
  • // testscores vary in number from one student to
    another

46
  • // determine grade
  • if (averagegt90)
  • return 'A'
  • else if (averagegt80)
  • return 'B'
  • else if (average gt 70)
  • return 'C'
  • else if (average gt60)
  • return 'D'
  • else
  • return 'F'
  • // method to return a student's name, scores, and
    grade as string
  • public String toString()
  • String str
  • str String.format("-10s -10s", firstName,
    lastName)
  • for (double score testScores)
  • strstr " " score

47
(No Transcript)
48
Two-Dimensional Arrays
  • Data is sometimes in table form (difficult to
    represent using a one-dimensional array).
  • To declare/instantiate a two-dimensional array
  • dataType arrayName newdataTypeintExp1
    intExp2
  • To access a component of a two-dimensional array
  • arrayNameindexExp1indexExp2
  • intExp1, intExp2 gt 0
  • indexExp1 row position
  • indexExp2 column position

49
Two-Dimensional Arrays
  • Can specify different number of columns for each
    row (ragged arrays).
  • Three ways to process two-dimensional arrays
  • Entire array.
  • Particular row of array (row processing).
  • Particular column of array (column processing).
  • Processing algorithms is similar to processing
    algorithms of one-dimensional arrays.

50
doublesales new double105
Two-Dimensional Arrays
51
Accessing Two-Dimensional Array Components
52
Two-Dimensional Arrays Special Cases
Java allows us to specify a different number of
columns in each row
Each row must be instantiated separately. E.g. int
faithnew int 5 - 5 rows faith0new
int 6 faith1 new int2 faith2 new
int5 and so on.
53
Two-Dimensional Arrays Processing
Initialization for (row 0 row lt matrix.length
row) for (col 0 col lt
matrixrow.length col)
matrixrowcol 10
Print for (row 0 row lt matrix.length
row) for (col 0 col lt
matrixrow.length col)
System.out.printf("7d",
matrixrowcol) System.out.println() I
nput for (row 0 row lt matrix.length row)
for (col 0 col lt matrixrow.length
col) matrixrowcol
console.nextInt()
54
  • // to manipulate two dimensional arrays
  • import java.util.
  • import java.io.
  • public class array5
  • public static void main (String ala) throws
    FileNotFoundException
  • Scanner inputF new Scanner(new
    FileReader("array5.txt"))
  • PrintWriter outputF new PrintWriter("array5.out
    ")
  • // to declare two dimensional array
  • int boys
  • // to instantiate the array
  • boys new int 56
  • // to read data from the file into the array
  • int row, col
  • for(row0 rowltboys.length row)

55
(No Transcript)
56
Two-Dimensional Arrays Processing
Sum by row // to sum by row, eg. row number
4, i.e 5th row row4 int
sum0 for(col0 colltboysrow.length
col) sum sum boysrowcol
System.out.println() System.out.println()
System.out.println("The sum of
row"(row1)"" sum)
57
Two-Dimensional Arrays Processing
  • Sum by Column
  • // to sum by column, eg. column number 3, i.e
    4th column
  • col3
  • sum0
  • for(row0 rowltboys.length row)
  • sum sum boysrowcol
  • System.out.println()
  • System.out.println("The sum of
    column"(col1)"" sum)

58
Two-Dimensional Arrays Processing
  • Largest Element of a Row
  • // to find the largest element of a row (say row
    2)
  • row2
  • lgestboys20 // assumes that the
    first element of the row is the largest
  • for(col0 colltboys0.length col)
  • if(boysrowcolgtlgest)
  • lgestboysrowcol
  • System.out.println()
  • System.out.println("The largest element of
    row"(row1)"" lgest)

59
Two-Dimensional Arrays Processing
  • Largest Element of a Column
  • / to find the largest element of a column 3
  • col3
  • int lgest
  • lgestboys03 // assumes that the
    first element of the column is the largest
  • for(row0 rowltboys.length row)
  • if(boysrowcolgtlgest)
  • lgestboysrowcol
  • System.out.println()
  • System.out.println("The largest element of
    column"(col1)"" lgest)

60
Two-Dimensional Arrays Processing
  • Largest Element of each Row
  • // to find the largest element in each row
  • for(row0 rowltboys.length row)
  • lgestboysrow0
  • for(col0 colltboysrow.length col)
  • if(lgestltboysrowcol)
  • lgestboysrowcol
  • System.out.println()
  • System.out.println("The largest element of
    row"(row1)"" lgest)

61
Two-Dimensional Arrays Processing
  • Largest Element of each Column
  • // to find the largest element in each column
  • for(col0 colltboys0.length col)
  • lgestboys0col
  • for(row0 rowltboys.length row)
  • if(lgestltboysrowcol)
  • lgestboysrowcol
  • System.out.println()
  • System.out.println("The largest element of
    column"(col1)"" lgest)

62
  • // new method to print the contents of a matrix
  • public static void toprint(int boys)
  • int row, col
  • int presrow0
  • for(row0 rowltboys.length row)
  • for(col0colltboys0.length col)
  • if (row presrow)
  • System.out.printf("6d",boysrowcol )
  • else if (rowgtpresrow)
  • System.out.println()
  • System.out.printf("6d",boysrowcol )
  • presrowrow
  • System.out.println()

63
  • // new method to find the largest element in each
    row
  • public static void rowlarge(int boys)
  • int row, col, lgest
  • for(row0 rowltboys.length row)
  • lgestboysrow0
  • for(col0 colltboysrow.length col)
  • if(lgestltboysrowcol)
  • lgestboysrowcol
  • System.out.println()
  • System.out.println("The largest element of
    row"(row1)"" lgest)
  • // method to find the largest element in each
    column
  • public static void colarge(int boys)

64
  • //main method that calls the other methods
  • import java.util.
  • import java.io.
  • public class array6
  • public static void main (String ala) throws
    FileNotFoundException
  • Scanner inputF new Scanner(new
    FileReader("array5.txt"))
  • PrintWriter outputF new PrintWriter("array5.out
    ")
  • int mike
  • mike new int 56
  • // to read data from the file into the array
  • int row, col
  • for(row0 rowltmike.length row)
  • for(col0 colltmike0.length col)
  • mikerowcol inputF.nextInt()
  • // to call the methods
  • toprint(mike)

65
Multidimensional Arrays
  • Can define three-dimensional arrays or
    n-dimensional arrays (n can be any number).
  • Syntax to declare and instantiate array
  • dataType arrayName new
  • dataTypeintExp1intExp2intExpn
  • Syntax to access component
  • arrayNameindexExp1indexExp2indexExpn
  • intExp1, intExp2, ..., intExpn positive
    integers
  • indexExp1,indexExp2, ..., indexExpn
    non-negative integers

66
Loops to Process Multidimensional Arrays
double carDealers new double1057
For (i 0 i lt 10 i) for (j 0 j lt 5
j) for (k 0 k lt 7 k)
carDealersijk 10.00
67
  • //to handle the input data as three dimensional
    array (2 blocks)
  • import java.util.
  • import java.io.
  • public class array7
  • public static void main (String ala) throws
    FileNotFoundException
  • Scanner inputF new Scanner(new
    FileReader("array7.txt"))
  • PrintWriter outputF new PrintWriter("array5.out
    ")
  • int boys
  • boys new int 253
  • // to read data from the file into the array
  • int i,j,k
  • for(i0 ilt2 i)
  • for(j0 jlt5 j)
  • for(k0 klt3 k)
  • boysijk inputF.nextInt()
  • // to print

68
(No Transcript)
69
Chapter Summary
  • Arrays
  • Definition
  • Uses
  • Different arrays
  • One-dimensional
  • Two-dimensional
  • Multidimensional (n-dimensional)
  • Arrays of objects
  • Parallel arrays

70
Chapter Summary
  • Declaring arrays
  • Instantiating arrays
  • Processing arrays
  • Entire array
  • Row processing
  • Column processing
  • Common operations and methods performed on arrays
  • Manipulating data in arrays
Write a Comment
User Comments (0)
About PowerShow.com