Chapter 9: Arrays J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

Slides:



Advertisements
Similar presentations
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Fall 2013.
Advertisements

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.
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.
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 7: User-Defined Methods
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.
© 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
1 Chapter 8 Multi-Dimensional Arrays. 2 1-Dimentional and 2-Dimentional Arrays In the previous chapter we used 1-dimensional arrays to model linear collections.
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.
Programming Fundamentals I (COSC-1336), Lecture 8 (prepared after Chapter 7 of Liang’s 2011 textbook) Stefan Andrei 4/23/2017 COSC-1336, Lecture 8.
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 8 Multidimensional 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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Chapter 4: Control Structures II
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.
CiS 260: App Dev I. 2 Introduction to Arrays n An array is an object that contains a collection of components (_________) of the same data type. n For.
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.
CiS 260: App Dev I. 2 Introduction to Arrays n An array is an object that contains a collection of components (_________) of the same data type. n For.
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.
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.
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.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
EGR 2261 Unit 10 Two-dimensional Arrays
Chapter 7 Multidimensional Arrays
Chapter 8: Arrays Starting Out with C++ Early Objects Ninth Edition
Computer Programming BCT 1113
Chapter 5: Control Structures II
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.
Repetition-Counter control Loop
SELECTION STATEMENTS (1)
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 8 Multidimensional Arrays
Chapter 7 Multidimensional Arrays
Java Programming: Program Design Including Data Structures
Chapter 7 Multidimensional Arrays
Chapter 8 Multidimensional Arrays
Arrays.
Presentation transcript:

Chapter 9: Arrays J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

Java Programming: From Problem Analysis to Program Design2 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.

Java Programming: From Problem Analysis to Program Design3 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 Motivation Write a program to read 5 numbers, find their sum and print them in reverse order. import java.util.*; public class RevOrder{ static Scanner console = new Scanner(System.in); public static void main(String[] args){ int item0, item1, item2, item3, item4; int sum; System.out.println("Enter 5 numbers: "); item0=console.nextInt(); item1=console.nextInt(); item2=console.nextInt(); item3=console.nextInt(); item4=console.nextInt(); sum = item0+item1+item2+item3+item4; System.out.println("Sum = " + sum); System.out.print("Numbers is reverse = "); System.out.println(item4+" "+item3+" "+item2+" "+item1+" "+item0); } } Enter 5 numbers: Sum = 26 Numbers is reverse =

Java Programming: From Problem Analysis to Program Design5 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.

Java Programming: From Problem Analysis to Program Design6 One-Dimensional Arrays  Syntax to instantiate an array:  dataType[ ] arrayName; arrayName = new dataType[intExp]  dataType[ ] arrayName = new dataType[intExp]  dataType[ ] arrayName1, arrayName2;  Syntax to access an array component:  arrayName[indexExp]  intExp = number of components in array >= 0  0 <= indexExp < intExp

Java Programming: From Problem Analysis to Program Design7 int[] num = new int[5]; Array num

Java Programming: From Problem Analysis to Program Design8 Array list

Java Programming: From Problem Analysis to Program Design9 int arraySize; System.out.print("Enter the size of " + "the array: "); arraySize = console.nextInt(); System.out.println(); int[] list = new int[arraySize]; Specifying Array Size During Program Execution

Java Programming: From Problem Analysis to Program Design10 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, sales[0]= 12.25, sales[1]= 32.50, sales[2]= 16.90, sales[3]= 23.00, and sales[4]=  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. Array Initialization During Declaration

Java Programming: From Problem Analysis to Program Design11  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}; Arrays and the Instance Variable length

Java Programming: From Problem Analysis to Program Design12  This statement creates the array numList of 10 components and initializes each component to 0. int[] numList = new int[10];  The value of numList.length is 10.  These statements store 5, 10, 15, and 20, respectively, in the first four components of numList. numList[0] = 5; numList[1] = 10; numList[2] = 15; numList[3] = 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. Arrays and the Instance Variable length

Java Programming: From Problem Analysis to Program Design13  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 for (i = 0; i < list.length; i++) list[i] = console.nextInt(); for (i = 0; i < list.length; i++) System.out.print(list[i] + " "); Processing One-Dimensional Arrays

Java Programming: From Problem Analysis to Program Design14 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: From Problem Analysis to Program Design15 Code to Initialize Array to Specific Value (10.00) for (index = 0; index < sales.length; index++) sales[index] = 10.00;

Java Programming: From Problem Analysis to Program Design16 Code to Read Data into Array for (index = 0; index < sales.length; index++) sales[index] = console.nextDouble();

Java Programming: From Problem Analysis to Program Design17 Code to Print Array for (index = 0; index < sales.length; index++) System.out.print(sales[index] + " ");

Java Programming: From Problem Analysis to Program Design18 Code to Find Sum and Average of Array 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;

Java Programming: From Problem Analysis to Program Design19 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: From Problem Analysis to Program Design20 Determining Largest Element in Array

//Program to read five numbers, find their sum, and //print the numbers in the reverse order. import java.util.*; public class ReversePrintII { static Scanner console = new Scanner(System.in); public static void main(String[] args) { int[] items = new int[5]; //declare an array item of //five elements int sum; System.out.println("Enter five integers:"); sum = 0; for (int counter = 0; counter < items.length; counter++) { items[counter] = console.nextInt(); sum = sum + items[counter]; } System.out.println("The sum of the numbers = “+ sum); Java Programming: From Problem Analysis to Program Design21

System.out.print("The numbers in the reverse " + "order are: "); //print the numbers in the reverse order for (int counter = items.length - 1; counter >= 0; counter--) System.out.print(items[counter] + " "); System.out.println(); } } Java Programming: From Problem Analysis to Program Design22

Java Programming: From Problem Analysis to Program Design23 Array Index Out of Bounds  An array is in bounds if: 0 <= index <= arraySize – 1  If index arraySize : ArrayIndexOutOfBoundsException exception is thrown.  Base address: Memory location of the first component in an array.  Base address of list is the address of list[0].

Java Programming: From Problem Analysis to Program Design24 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 int[10]; double[] doubleNumList = new double[15]; int number; arraysAsFormalParameter(intList, doubleNumList, number);

Java Programming: From Problem Analysis to Program Design25 The Assignment Operators and Arrays

Java Programming: From Problem Analysis to Program Design26 The Assignment Operators and Arrays

Java Programming: From Problem Analysis to Program Design27 for (int index = 0; index < listA.length; index++) listB[index] = listA[index]; The Assignment Operators and Arrays

Java Programming: From Problem Analysis to Program Design28 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.

Java Programming: From Problem Analysis to Program Design29 Relational Operators and Arrays 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 false; return true; } if (isEqualArrays(listA, listB))...

Java Programming: From Problem Analysis to Program Design30 Methods for Array Processing public static void fillArray(int[] list, int noOfElements) { int index; for (index = 0; index < noOfElements; index++) list[index] = console.nextInt(); }

Java Programming: From Problem Analysis to Program Design31 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 noOfElements) { int index; int sum = 0; for (index = 0; index < noOfElements; index++) sum = sum + list[index]; return sum; } Methods for Array Processing

Java Programming: From Problem Analysis to Program Design32 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, int noOfElements) { int index; for (index = 0; index < noOfElements; index++) list2[index] = list1[index]; } Methods for Array Processing

Java Programming: From Problem Analysis to Program Design33 Parallel Arrays  Arrays are parallel if the corresponding components hold related information. int [] studentId = new int[50]; char[] courseGrade = new char[50]; studentId[3] and courseGrade[3] holds the data for the same student. studentId courseGrade 2345 A 4563 C 4590 C 2404 B

Java Programming: From Problem Analysis to Program Design34 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";  You can use String methods to work with the objects of nameList. nameList[0].equals(“Amanda Green”) // true nameList[4].substring(0,5) //Mandy

Java Programming: From Problem Analysis to Program Design35 Array of String Objects

Java Programming: From Problem Analysis to Program Design36 Arrays and Variable Length Parameter List  The syntax to declare a variable length formal parameter (list) is: dataType... identifier

Java Programming: From Problem Analysis to Program Design37 Arrays and Variable Length Parameter List public static double largest(double... numList) { double max; int index; if (numList.length != 0) { max = list[0]; for (index = 1; index < numList.length; index++) { if (max < numList [index]) max = numList [index]; } return max; } return 0.0; }

Java Programming: From Problem Analysis to Program Design38 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, , 112.0, 77, 11, 22, 86.62); System.out.println(largest(numberList));

39 Rules to follow when using a variable length formal parameter list: 1.A method can have both a variable length formal parameter and other formal parameter. public static void myMethod (String name, double num, int … intList) 2.A method can have at most one variable length formal parameter. 3.If a method has both a variable length formal parameter and other formal parameter, then the variable length formal parameter must be the last). Arrays and Variable Length Parameter List

Java Programming: From Problem Analysis to Program Design40 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.

Java Programming: From Problem Analysis to Program Design41 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 list[0]. In the next iteration, the value of num is list[1], and so on. for (double num : numList) { if (max < num) max = num; }

42 [Red][Brown][Black][White][Gray] [GM] [Ford]63664 [Toyota]35367 [BMW]82753 [Nissan] [Volvo]15797 Two-Dimensional Arrays inStock

Java Programming: From Problem Analysis to Program Design43 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];  To access a component of a two-dimensional array: arrayName[indexExp1][indexExp2];  intExp1, intExp2 >= 0  indexExp1 = row position  indexExp2 = column position

Java Programming: From Problem Analysis to Program Design44 double[][]sales = new double[10][5]; Two-Dimensional Arrays

Java Programming: From Problem Analysis to Program Design45 Accessing Two-Dimensional Array Components

46 int [][] matrix = new int[20][15]; 20 rows 15 columns matrix.length = 20 //number of rows  Each row of matrix is 1-D array matrix.[0].length = 15 //# of columns in 1 st row matrix.[1].length = 15 // # of columns in 2 nd row Two-Dimensional Arrays

47 Two-Dimensional Arrays: Special Cases  Can specify different number of columns for each row (ragged arrays). In this case, each row must be instantiated separately.

48 Two-Dimensional Arrays: Special Cases To create this array, first we create 1-D array board of 5 rows: int[] board = new int[5]; board[0] = new int[6]; board[1] = new int[2]; board[2] = new int[2]; board[3] = new int[3]; board[4] = new int[4];

49 Two Dimensional Array Initialization During Declaration int[][] board = {{2,3,1}, {15,25,13}, {20, 4, 7}}; [0][1][2] [0]231 [1] [2]2047 board What is the array created after this statement: int[][] table = {{2,3,1,5}, {15,25}, {4, 23, 45}};

Java Programming: From Problem Analysis to Program Design50 Two-Dimensional 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: From Problem Analysis to Program Design51 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: From Problem Analysis to Program Design52 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); } Two-Dimensional Arrays: Processing

Java Programming: From Problem Analysis to Program Design53 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: Processing

Java Programming: From Problem Analysis to Program Design54 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); } Two-Dimensional Arrays: Processing

Java Programming: From Problem Analysis to Program Design55 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); } Two-Dimensional Arrays: Processing

Java Programming: From Problem Analysis to Program Design56 Multidimensional Arrays  Can define three-dimensional arrays or n-dimensional arrays (n can be any number).  Syntax to declare and instantiate array: d ataType[][]…[] 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: From Problem Analysis to Program Design57 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;

Code Detection // This program checks whether the message received at the destination // is error-free. If there is an error in the message, then the // program outputs an error message and asks for retransmission. import java.util.*; public class CodeDetection { static Scanner console = new Scanner(System.in); public static void main(String[] args) { int codeLength; //Step 1 System.out.print("Enter the length of " + " the code: "); //Step 2 codeLength = console.nextInt(); //Step 3 System.out.println(); int[] codeArray = new int[codeLength]; //Step 4 readCode(codeArray); //Step 5 compareCode(codeArray); //Step 6 } Java Programming: From Problem Analysis to Program Design58

public static void readCode(int[] list) { System.out.print("Enter the secret code: "); for (int count = 0; count < list.length; count++) list[count] = console.nextInt(); System.out.println(); } Java Programming: From Problem Analysis to Program Design59

public static void compareCode(int[] list) { //Step a: Declare the variables int length2; int digit; boolean codeOk; int count; codeOk = true; //Step b System.out.println("Enter the length of the copy of " + "the secret code \nand a copy of " + "the secret code: "); length2 = console.nextInt(); //Step c if (list.length != length2) //Step d { System.out.println("The original code and " + "its copy are not of " + "the same length."); return; } System.out.println("Code Digit Code Digit " + "Copy"); //Step e Java Programming: From Problem Analysis to Program Design60

for (count = 0; count < list.length; count++) //Step f { digit = console.nextInt(); //Step f.1 System.out.printf("%5d %15d", list[count], digit); //Step f.2 if (digit != list[count]) //Step f.3 { System.out.println(" corresponding code " + "digits not the same"); codeOk = false; } else System.out.println(); } if (codeOk) //Step g System.out.println("Message transmitted OK."); else System.out.println("Error in transmission. " + "Retransmit!!"); } } Java Programming: From Problem Analysis to Program Design61

Java Programming: From Problem Analysis to Program Design62 Chapter Summary  Arrays  Definition  Uses  Different arrays  One-dimensional  Two-dimensional  Multidimensional (n-dimensional)  Parallel arrays

Java Programming: From Problem Analysis to Program Design63 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