Java Programming: Program Design Including Data Structures

Slides:



Advertisements
Similar presentations
Arrays. What is an array An array is used to store a collection of data It is a collection of variables of the same type.
Advertisements

Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
CHAPTER 10 ARRAYS II Applications and Extensions.
COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007.
1 Lecture 21:Arrays and Strings(cont.) Introduction to Computer Science Spring 2006.
1 Lecture 20:Arrays and Strings Introduction to Computer Science Spring 2006.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays.
Chapter 9: Arrays and Strings
Chapter 9: Arrays and Strings
Chapter 9: Arrays and Strings
Chapter 8 Arrays and Strings
Arrays. Objectives Learn about arrays Explore how to declare and manipulate data into arrays Learn about “array index out of bounds” Become familiar with.
Arrays (Part II). Two- and Multidimensional Arrays Two-dimensional array: collection of a fixed number of components (of the same type) arranged in two.
1 Lecture 22:Applications of Arrays Introduction to Computer Science Spring 2006.
© 2011 Pearson Education, publishing as Addison-Wesley 1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 6 focuses.
Chapter 8 Arrays and Strings
EGR 2261 Unit 8 One-dimensional Arrays  Read Malik, pages in Chapter 8.  Homework #8 and Lab #8 due next week.  Quiz next week.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Java Programming: From Problem Analysis to Program Design, 4e
ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays.
Chapter 9: Arrays J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second Edition.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
1 Topic: Array Topic: Array. 2 Arrays Arrays In this chapter, we will : Learn about arrays Learn about arrays Explore how to declare and manipulate data.
1 Chapter 9 Arrays Java Programming from Thomson Course Tech, adopted by kcluk.
Chapter 5: ARRAYS ARRAYS. Why Do We Need Arrays? Java Programming: From Problem Analysis to Program Design, 4e 2  We want to write a Java program that.
Java Programming: Chapter 9: Arrays
Opening Input/Output Files ifstream infile; ofstream outfile; char inFileName[40]; char outFileName[40]; coutinFileName;
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
1 Chapter 9 Arrays Java Programming from Thomson Course Tech, adopted by kcluk.
Chapter 9 Arrays. Chapter Objectives Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning of “array index.
Chapter 9 Arrays. Chapter Objectives Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning of “array index.
Chapter 9 Introduction to Arrays Fundamentals of Java.
1 Why do we need arrays? Problem - Input 5 test scores => int test1,test2,test3,test4,test5 100 test scores? 10,000 employees? A structured data type is.
Lesson 9 Arrays. Miscellaneous About Arrays An array is an object. Because of this, the array name is a reference variable Therefore, in order to start.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Lecture 7: Arrays Michael Hsu CSULA 3 Opening Problem Read one hundred numbers, compute their average, and find out how many numbers are above the average.
Array 1 ARRAY. array 2 Learn about arrays. Explore how to declare and manipulate data into arrays. Understand the meaning of “array index out of bounds.”
1 Arrays and Variable Length Parameter List  The syntax to declare a variable length formal parameter (list) is: dataType... identifier.
Chapter 9: Arrays J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Arrays Chapter 7.
1 Chapter 7 Multidimensional Arrays. 2 Motivations You can use a two-dimensional array to represent a matrix or a table.
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Chapter VII: Arrays.
Chapter 7 User-Defined Methods.
EGR 2261 Unit 10 Two-dimensional Arrays
Write code to prompt for 5 grades, read them in, print “Thank you”, then reprint the 5 grades and their average. System.out.println(“Please enter grade.
Chapter 7 Multidimensional Arrays
Chapter 8: Arrays Starting Out with C++ Early Objects Ninth Edition
Computer Programming BCT 1113
© 2016 Pearson Education, Ltd. All rights reserved.
Basic Array Definition
Motivations Thus far, you have used one-dimensional arrays to model linear collections of elements. You can use a two-dimensional array to represent a.
User-Defined Functions
Chapter 6 Arrays Solution Opening Problem
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
Chapter 7 Multidimensional Arrays
EKT150 : Computer Programming
Lecture 9 Objectives Learn about arrays.
Chapter 6 Arrays.
Dr. Sampath Jayarathna Cal Poly Pomona
Chapter 8 Multidimensional Arrays
Chapter 7 Multidimensional Arrays
Chapter 7 Multidimensional Arrays
C++ Array 1.
Chapter 7 Multidimensional Arrays
Arrays.
Presentation transcript:

Java Programming: Program Design Including Data Structures Chapter 9: Arrays Java Programming: Program Design Including Data Structures

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 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 Java Programming: Program Design Including Data Structures

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 A 1 2 3 4 Data … A[1] Length: 5 First index: 0 Last index: 4 Java Programming: Program Design Including Data Structures

One-Dimensional Arrays Syntax to instantiate an array: dataType[ ] arrayName; arrayName = new dataType[intExp] dataType[ ] arrayName = new dataType[intExp] dataType[ ] arrayName1, arrayName2; Example int[] A; A = new int[5]; int[] B = new int[5]; int[] C = {11, 22, 33, 44, 55}; int[] E, F; Java Programming: Program Design Including Data Structures

One-Dimensional Arrays Syntax to access an array component: arrayName[indexExp] intExp = number of components in array >= 0 0 <= indexExp <= intExp Example A[0] = 100; A[4] = 500; A[2] = A[4] – A[0] + 1; A[5] = …  error (index out of bound) Java Programming: Program Design Including Data Structures

Array num int[] num = new int[5]; Java Programming: Program Design Including Data Structures

Array list Java Programming: Program Design Including Data Structures

Default Values All entries of an array are first initialized to the proper data type default value. Example int[] A = new A[3]; Currently the array is A[0] = 0 A[1] = 0 A[2] = 0 Type Default Value int double 0.0 boolean false String “” (empty) Java Programming: Program Design Including Data Structures

Using Arrays int[] A; A = new int[5]; //all entries are set to zero int[] E, F; A[0] = 100; A[4] = 500; for (int i=0; i<A.length; i++) { System.out.println(i + " " + A[i]); } E = A; //E same as A 0 100 1 0 2 0 3 0 4 0 Java Programming: Program Design Including Data Structures

Specifying Array Size During Program Execution … int arraySize; System.out.print("Enter the size of the array: "); arraySize = console.nextInt(); int[] list = new int[arraySize]; .. . Java Programming: Program Design Including Data Structures

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 sales[0]= 12.25, sales[1]= 32.50, etc. Array size is determined by the number of initial values within the braces If an array is declared and initialized simultaneously, do not use the operator new to instantiate the array object Java Programming: Program Design Including Data Structures

Arrays and the Instance Variable length A public instance variable length is associated with each array that has been instantiated length contains the size of the array length can be directly accessed in a program using the array name and the dot operator Valid indices of an array (say A) are: 0 … A.length - 1 Example: Here list.length is 6 int[] list = {10, 20, 30, 40, 50, 60}; List[0] List[5] Java Programming: Program Design Including Data Structures

Arrays and the Instance Variable length Create the array myList of 10 components and initialize each component to 0 int[] myList = new int[10]; The value of myList.length is 10 Java Programming: Program Design Including Data Structures

Arrays and the Instance Variable length (continued) These statements store 5, 10, 15, and 20, respectively, in the first four components of myList myList[0] = 5; myList[1] = 10; myList[2] = 15; myList[3] = 20; Can store the number of filled elements, in the array in a variable, say noOfElement Java Programming: Program Design Including Data Structures

Processing One-Dimensional Arrays Loops used to step through elements in array and perform operations int[] list = new int[100]; int i; for (i = 0; i < list.length; i++) //process list[i], the (i + 1)th //element of list list[i] = console.nextInt(); System.out.print(list[i] + " "); Java Programming: Program Design Including Data Structures

Arrays Some operations on arrays: Initialize Input data Output stored data Find largest/smallest/sum/average of elements double[] sales = new double[10]; int index; double largestSale, sum, average; Java Programming: Program Design Including Data Structures

Code to Initialize Array to Specific Value (10.00) for (index = 0; index < sales.length; index++) sales[index] = 10.00; Java Programming: Program Design Including Data Structures

Code to Read Data into Array for (index = 0; index < sales.length; index++) sales[index] = console.nextDouble(); Java Programming: Program Design Including Data Structures

Code to Print Array for (index = 0; index < sales.length; index++) System.out.print(sales[index] + " "); Java Programming: Program Design Including Data Structures

Code to Find Sum and Average of Array for (index = 0; index < sales.length; index++) sum = sum + sales[index]; if (sales.length != 0) average = sum / sales.length; else average = 0.0; Java Programming: Program Design Including Data Structures

Determining Largest Element in Array maxIndex = 0; for (index = 1; index < sales.length; index++) if (sales[maxIndex] < sales[index]) maxIndex = index; largestSale = sales[maxIndex]; Java Programming: Program Design Including Data Structures

Determining Largest Element in Array (continued) Java Programming: Program Design Including Data Structures

Array Index Out of Bounds An array is in bounds if: 0 <= index <= arraySize – 1 If index < 0 or index > arraySize: ArrayIndexOutOfBoundsException exception is thrown Base address: location of the first array component Java Programming: Program Design Including Data Structures

Declaring Arrays as Formal Parameters to Methods General syntax to declare an array as a formal parameter: dataType[] arrayName //receiving the call from the caller public static void myMethod1 (int[] listA, double[] listB, int num) { //...do something here } //making the call to a method int[] intList = new int[10]; double[] doublemyList = new double[15]; int number; myMethod1 (intList, doublemyList, number); Java Programming: Program Design Including Data Structures

Declaring Arrays as Formal Parameters to Methods Example: Method is called with an array parameter //receiving the call from the caller public static void myMethod1 (int[] listA, double[] listB, int num) { //...do something here } ... //making the call to a method int[] intList = {10, 20, 30, 40}; Int[] myMethod1 (intList, doublemyList, number); Java Programming: Program Design Including Data Structures

Declaring Arrays as Formal Parameters to Methods 0 11 1 21 2 31 3 41 Example: Method is called using an array parameter ... int[] intList = {10, 20, 30, 40}; int listSize = intList.length; myMethod1 (intList, listSize); for (int i=0; i<listSize; i++) { System.out.println(i + " " + intList[i]); } private static void myMethod1(int[] A, int n) { for (int i=0; i<n; i++) { A[i] += 1; System.out.println(i + " " + A[i]); 0 11 1 21 2 31 3 41 Java Programming: Program Design Including Data Structures

The Assignment Operators and Arrays Java Programming: Program Design Including Data Structures

The Assignment Operators and Arrays (continued) Java Programming: Program Design Including Data Structures

The Assignment Operators and Arrays (continued) for (int index = 0; index < listA.length; index++) listB[index] = listA[index]; Java Programming: Program Design Including Data Structures

Relational Operators Arrays if (listA == listB) ... The expression listA == listB determines if the values of listA and listB are the same (refer to the same array) To determine whether listA and listB contain the same elements, compare them component by component You can write a method that returns true if two int arrays contain the same elements Java Programming: Program Design Including Data Structures

Relational Operators and Arrays (continued) boolean isEqualArrays(int[] firstArray, int[] secondArray) { if (firstArray.length != secondArray.length) return false; for (int index = 0; index < firstArray.length; index++) if (firstArray[index] != secondArray[index]) return true; } if (isEqualArrays(listA, listB)) ... Java Programming: Program Design Including Data Structures

Methods for Array Processing //capture data from the keyboard public static void fillArray(int[] list, int noOfElements) { int index; for (index = 0; index < noOfElements; index++) list[index] = console.nextInt(); } Java Programming: Program Design Including Data Structures

Methods for Array Processing (continued) public static void printArray(int[] list, int noOfElements) { int index; for (index = 0; index < noOfElements; index++) System.out.print(list[index] + " "); } public static int sumArray(int[] list, int sum = 0; sum = sum + list[index]; return sum; Java Programming: Program Design Including Data Structures

Methods for Array Processing (continued) public static int indexLargestElement(int[] list, int noOfElements) { int index; int maxIndex = 0; for (index = 1; index < noOfElements; index++) if (list[maxIndex] < list[index]) maxIndex = index; return maxIndex; } public static void copyArray(int[] list1, int[] list2, for (index = 0; index < noOfElements; index++) list2[index] = list1[index]; Java Programming: Program Design Including Data Structures

Parallel Arrays firstName lastName Maria  Macarena 1 2 3 Juan Valdez Arrays are parallel if the corresponding components hold related information Java Programming: Program Design Including Data Structures

Arrays of Objects Can use arrays to manipulate objects Example: Create an array named array1 with N objects of type T: T[] array1 = new T[N] Can instantiate array1 as follows: for(int j=0; j <array1.length; j++) array1[j] = new T(); Java Programming: Program Design Including Data Structures

Array of String 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"; Java Programming: Program Design Including Data Structures

Array of String Objects (continued) Java Programming: Program Design Including Data Structures

Clock[] arrivalTimeEmp = new Clock[100]; Arrays of Objects Clock[] arrivalTimeEmp = new Clock[100]; Java Programming: Program Design Including Data Structures

Instantiating Array Objects for (int j = 0; j < arrivalTimeEmp.length; j++) arrivalTimeEmp[j] = new Clock(); Java Programming: Program Design Including Data Structures

Instantiating Array Objects arrivalTimeEmp[49].setTime(8, 5, 10); Java Programming: Program Design Including Data Structures

Arrays and Variable Length Parameter List The syntax to declare a variable length formal parameter (list) is: dataType ... identifier three dots It could be called using actual parameters such as myMethod (2, 4, 6, 1, 100, 3); myMethod (myArray); Java Programming: Program Design Including Data Structures

Arrays and Variable Length Parameter List (continued) public static double largest(int ... myList) { double max; int index; if (myList.length != 0) max = list[0]; for (index = 1; index < myList.length; index++) if (max < myList [index]) max = myList [index]; } return max; return 0.0; Instead of: int[] myList Java Programming: Program Design Including Data Structures

Arrays and Variable Length Parameter List (continued) 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)); Java Programming: Program Design Including Data Structures

foreach loop The syntax to use 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 Java Programming: Program Design Including Data Structures

foreach loop The for statement is read for each num in list sum = 0; for (double num : myDoubleList) sum = sum + num; The for statement is read for each num in list The identifier num is initialized to list[0] In the next iteration, the value of num is list[1], and so on Java Programming: Program Design Including Data Structures

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 = new dataType[intExp1][intExp2]; int [][] dayHourTemperature = new int[31][25]; int [][] genderEmployeeDept = double int [2][10]; Java Programming: Program Design Including Data Structures

Two-Dimensional Arrays To access a component of a two-dimensional array: arrayName[indexExp1][indexExp2]; intExp1, intExp2 >= 0 indexExp1 = row position indexExp2 = column position dayHourTemperature[01][01] = 41; … dayHourTemperature[01][24] = 40; dayHourTemperature[30][24] = 38; Java Programming: Program Design Including Data Structures

Two-Dimensional Arrays (continued) 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 Java Programming: Program Design Including Data Structures

double[][]sales = new double[10][5]; Two-Dimensional Arrays (continued) double[][]sales = new double[10][5]; Java Programming: Program Design Including Data Structures

Accessing Two-Dimensional Array Components Java Programming: Program Design Including Data Structures

Two-Dimensional Arrays: Special Cases Java Programming: Program Design Including Data Structures

Two-Dimensional Arrays: Processing Initialization for (row = 0; row < matrix.length; row++) for (col = 0; col < matrix[row].length; col++) matrix[row][col] = 10; Print for (row = 0; row < matrix.length; row++) { for (col = 0; col < matrix[row].length; col++) System.out.printf("%7d", matrix[row][col]); System.out.println(); } Java Programming: Program Design Including Data Structures

Two-Dimensional Arrays: Processing (continued) Input for (row = 0; row < matrix.length; row++) for (col = 0; col < matrix[row].length; col++) matrix[row][col] = console.nextInt(); 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); } Java Programming: Program Design Including Data Structures

Two-Dimensional Arrays: Processing (continued) 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); } Java Programming: Program Design Including Data Structures

Two-Dimensional Arrays: Processing (continued) 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); } Java Programming: Program Design Including Data Structures

Two-Dimensional Arrays: Processing (continued) Largest Element in Each Column for (col = 0; col < matrix[0].length; col++) { largest = matrix[0][col]; for (row = 1; row < matrix.length; row++) if (largest < matrix[row][col]) largest = matrix[row][col]; System.out.println("The largest element of col " + (col + 1) + " = " + largest); } Java Programming: Program Design Including Data Structures

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 dataType[intExp1][intExp2]…[intExpn]; Syntax to access component: arrayName[indexExp1][indexExp2]…[indexExpn] intExp1, intExp2, ..., intExpn = positive integers indexExp1,indexExp2, ..., indexExpn = non-negative integers Java Programming: Program Design Including Data Structures

Loops to Process Multidimensional 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; Java Programming: Program Design Including Data Structures

Programming Example: Text Processing Reads given text; outputs the text as is; prints number of lines and number of times each letter appears in text Input: File containing text to be processed Output: File containing text, number of lines, number of times each letter appears in text Java Programming: Program Design Including Data Structures

Programming Example Solution: Text Processing An array of 26 representing the letters in the alphabet Three methods: copyText characterCount writeTotal Value in appropriate index is incremented using methods and depends on character read from text Java Programming: Program Design Including Data Structures

Chapter Summary Arrays Different arrays Definition Uses One-dimensional Two-dimensional Multidimensional (n-dimensional) Arrays of objects Parallel arrays Java Programming: Program Design Including Data Structures

Chapter Summary (continued) Declaring arrays Instantiating arrays Processing arrays Entire array Row processing Column processing Common operations and methods performed on arrays Manipulating data in arrays Java Programming: Program Design Including Data Structures