Chapter 8 Arrays and the ArrayList Class Introduction to Arrays.

Slides:



Advertisements
Similar presentations
Chapter 10 Introduction to Arrays
Advertisements

1 Fall 2008ACS-1903 Chapter 8: Arrays 8.1 – 8.8 Introduction to Arrays Processing Array Contents Passing Arrays as Arguments to Methods Some Useful Array.
Introduction to Computers and Programming Lecture 15: Arrays Professor: Evan Korth New York University.
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.
Copyright © 2012 Pearson Education, Inc.
CS0007: Introduction to Computer Programming Introduction to Arrays.
© 2011 Pearson Education, publishing as Addison-Wesley 1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 6 focuses.
Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.
Chapter 7: Arrays and the ArrayList Class
© 2012 Pearson Education, Inc. All rights reserved. Lecture 2 (Chapter 8): Arrays and the ArrayList Class Starting Out with Java: From Control Structures.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: From Control Structures through Objects Third Edition.
One Dimensional Array. Introduction to Arrays Primitive variables are designed to hold only one value at a time. Arrays allow us to create a collection.
Chapter 7: Arrays and the ArrayList Class
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 8: Arrays and the ArrayList Class Starting Out with Java From Control.
A First Book of ANSI C Fourth Edition
JAVA Array 8-1 Outline  Extra material  Array of Objects  enhanced-for Loop  Class Array  Passing Arrays as Arguments to Methods  Returning Arrays.
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.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 8: Arrays.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 8: Arrays and the ArrayList Class Starting Out with Java: From.
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.
Introduction to Collections Arrays. Collections Collections allow us to treat a group of values as one collective entity. The array is a collection of.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
1 Building Java Programs Chapter 7: Arrays These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted, sold, or.
1 Methods Introduction to Methods Passing Arguments to a Method More About Local Variables Returning a Value from a Method Problem Solving with Methods.
CS 139-Programming Fundamentals Lecture 11B - Arrays Adapted from a presentation by Dr. Rahman Fall 2014.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
8-1 Chapter-7 Part1 Introduction to Arrays –Array Types –Creating/Declaring Arrays –Initializing Arrays –Processing Array Contents –Passing Arrays as Arguments.
Arrays Chapter 6. Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define methods that.
11 PART 2 ARRAYS. 22 PROCESSING ARRAY ELEMENTS Reassigning Array Reference Variables The third statement in the segment below copies the address stored.
BIT115: Introduction to Programming
Two Dimensional Arrays Found in chapter 8, Section 8.9.
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.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Chapter 7: Arrays and the ArrayList Class Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
CHAPTER 6 ARRAYS IN C 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 F. Alakeel.
Copyright © 2013 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Third Edition by Tony Gaddis.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Chapter 7 Arrays…. 7-2 Arrays An array is an ordered list of values An array of size N is indexed from.
Data Structures & Algorithms CHAPTER 2 Arrays Ms. Manal Al-Asmari.
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.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Chapter 8 Arrays and the ArrayList Class Multi-Dimensional Arrays.
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Chapter VII: Arrays.
CSC 211 Java I for loops and arrays.
Array Review CS 139 – November 28, 2007.
Chapter Topics Chapter 7 discusses the following main topics:
Chapter 7 Part 1 Edited by JJ Shepherd
Arrays, Searching and Sorting
New Structure Recall “average.cpp” program
Chapter 6 Arrays Solution Opening Problem
Chapter 7A: Arrays and the ArrayList Class
Array Review CS 139 – November 28, 2007.
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.
Object Oriented Programming in java
BIT115: Introduction to Programming
Starting Out with Programming Logic & Design
int [] scores = new int [10];
Building Java Programs
Array Review CS 139 – November 28, 2007.
Dr. Sampath Jayarathna Cal Poly Pomona
Dr. Sampath Jayarathna Cal Poly Pomona
Programming Fundamentals
Presentation transcript:

Chapter 8 Arrays and the ArrayList Class Introduction to Arrays

2 Contents I. What is an Array? II. Processing Array Elements III. Passing Arrays As Arguments to Methods IV. Some Useful Array Algorithms and Operations V. Returning Arrays from Methods VI. The Sequential Search Algorithm

3 I. What is an Array? 1. One-Dimensional Arrays 2. Accessing Array Elements 3. Inputting and Outputting Array Contents 4. Java Performs Bounds Checking 5. Watch Out for Off-by-One Errors 6. Array Initialization 7. Alternate Array Declaration Notation

4 I.1. One-Dimensional Arrays An one-dimensional array (array) is an object that can store a group of value, all of the same type. Declaration of an array reference variable numbers. int[] numbers; The numbers variable can reference an array of int values. Creating an array of 10 int values: number = new int[10]; Size of array

5 I.1. One-Dimensional Arrays int count; double number; char letter; int[] numbers = new int[5]; 1234 Enough memory to hold one int Enough memory to hold one double A Enough memory to hold one char 0 numbers variable Ele men t 0 0 Ele men t 1 0 Ele men t 2 0 Ele men t 3 0 Ele men t 4

6 I.1. One-Dimensional Arrays Examples: int[] numbers = new int[5]; float[] temperatures = new float[100]; char[] letters = new char[41]; long[] units = new long[50]; double[] sizes = new double[1200]; final int NUM_ELEMENTS = 5; int[] numbers = new int[NUM_ELEMENTS]; Once an array is created, its size cannot be changed. By default, Java initializes array elements with 0.

7 I.2. Accessing Array Elements Each element in an array is assigned a number known as a subscript. A subscript is used as an index to point a specific element within an array. The first element is assigned the subscript 0, the second element is assigned 1, and so forth. Each element in an array can be used as a variable. int[] numbers = new int[5]; 0 numbers variable subscript

8 I.2. Accessing Array Elements Each element in the array is accessed by its subscript. int[] numbers = new int[5]; numbers[0] = 20; numbers[1] = 25; numbers[2] = 30; numbers[3] = 35; numbers[4] = 40; 20 numbers variable numb ers[ 0] 25 numb ers[ 1] 30 numb ers[ 2] 35 numb ers[ 3] 40 numb ers[ 4]

9 I.3. Inputting and Outputting Array Contents

10 I.3. Inputting and Outputting Array Contents

11 I.4. Java Performs Bounds Checking Java performs array bounds checking. It does not allow a statement to use a subscript that is outside the range of valid subscripts for an array. int[] values = new int[10]; Java will not allow a statement to use a subscript that is less than 0 or greater than 9 with this array. Java will display a runtime error message if a statement that uses an invalid subscript executes.

12 I.5. Watch Out for Off-by-One Errors Because array subscript start at 0 rather than 1, you have to careful not to perform an off-by-one error. //This code has an off-by-one error. int[] numbers = new int[100]; for(int index = 1; index <= 100; index++) numbers[index] = 99; The first element, which is at subscript 0, is skipped. The program will crash because 100 is an invalid subscript.

13 I.6. Array Initialization Java allows us to initialize an array's elements when we create the array. int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; Java automatically creates the array and stores the values in the initialization list in it. Java determines the size of the array by the number of items in the initialization list. The values are stored in the array elements in the order they appear in the list. The first value, 31, is stored in days[0], the second value, 28, is stored in days[1], and so forth.

14 I.7. Alternate Array Declaration Notation Java allows us to use two different styles when declaring array reference variables. int[] numbers; int numbers[]; The difference between the two styles is notices when more than one variable is declared in the same statement. int[] numbers, codes, scores; int numbers[], codes, scores;

15 Checkpoint 8.1 Write a statements that create the following arrays” a. A 100-element int array referenced by the variable employeeNumbers. b. A 25-element double array referenced by the variable payRates. c. A 14-element float array referenced by the variable miles.

16 Checkpoint 8.2 What's wrong with the following array declarations? int[] readings = new int[-1]; double[] measurements = new double[4.5]; 8.3 What would the valid subscript values be in a four-element array of doubles ? 8.4 What is the difference between an array's size declarator and a subscript? 8.5 What does it mean for a subscript to be out- of-bounds?

17 Checkpoint 8.6 What happens in Java when a program tries to use a subscript that is out-of-bounds? 8.7 What is the output of the following code? int[] values = new int[5]; for(int count = 0; count < 5; count++) values[count] = count + 1; for(int count = 0; count < 5; count++) System.out.println(values[count]); 8.8 Write a statement that creates and initializes a double array with the following values: 1.7, 6.4, 8.9, 3.1, and 9.2. How many elements are in the array?

18 II. Processing Array Elements 1. Processing Array Elements 2. Array Length 3. The Enhanced for Loop 4. Letting the User Specify an Array's Size 5. Reassigning Array Reference Variables 6. Copying Arrays

19 II.1. Processing Array Elements Processing array elements is no different from processing other variables. grossPay = hours[3] * payRate; int[] score = {7, 8, 9, 10, 11}; ++score[2]; score[4]++; amount[count--];

20 II.2. Array Length Each array in Java has a public field named length. This field contains the number of elements in the array. double[] temperatures = new double[25];... for(int i = 0; i < temperatures.length; i++) System.out.println(temperatures[i]); The largest subscript in an array is length-1.

21 II.3. The Enhanced for Loop Java provides a specialized version of the for loop that, in many circumstances, simplifies array processing. for(dataType elementVariable : array) statement; For example: int[] numbers = { 3, 6, 9 }; for(int val : numbers) System.out.println(val);

22 II.3. The Enhanced for Loop When you need to access the values that are stored in an array, from the first element to the last element, the enhanced for loop is simpler to use than the traditional for loop. We cannot use the enhanced for loop as follows: If we need to change the contents of an array element If we need to work through the array elements in reverse order If we need to access some of the array elements, but not all of them

23 II.3. The Enhanced for Loop If we need to simultaneously work with two or more arrays within the loop If we need to refer to the subscript number of a particular element

24 II.4. Letting the User Specify an Array's Size Java allows us to use an integer variable to specify an array's size declarator. This makes it possible to allow the user to specify an array's size.

25

26 II.5. Reassigning Array Reference Variables It is possible to reassign an array reference variable to a different array. //Create an array referenced by the numbers variable. int[] numbers = new int[10]; //Reassign numbers to a new array. numbers = new int[5]; address The numbers variables holds the address of an int array The ten-element int array previously referenced A five-element int array

27 II.6. Copying Arrays An array is an object. An array and a reference variable are two separate entities. int[] array1 = { 2, 4, 6, 8, 10}; int[] array2 = array1; This does not copy array1. Both array1 and array2 reference the same array An int array addres s The array1 variable holds the address of an int array. addres s The array2 variable holds the address of an int array.

28 II.6. Copying Arrays To copy an array we need to copy the individual elements of one array to another. Usually, this is best done with a loop, such as the following: int[] firstArray = { 5, 10, 15, 20, 25 }; int[] secondArray = new int[5]; for(int index = 0; index < firstArray.length; index ++) secondArray[index] = firstArray[index];

29 Checkpoint 8.9 Look at the following statements: int[] numbers1 = { 1, 3, 6, 9}; int[] numbers2 = { 2, 4, 6, 8}; Write a statement that multiplies element 0 of the numbers1 array by element 3 of the numbers2 array and assigns the result to the result variable A program uses a variable named array that references an array of integers. We do not know the number of elements in the array. Write a for loop that stores -1 in each element of the array.

30 Checkpoint 8.11 A program has the following declaration: double[] values; Write code that asks the user for the size of the array and then creates an array of the specified size, referenced by the values variables Look at the following statememts: int[] a = {1, 2, 3, 4, 5, 6, 7}; int[] b = new int[7]; Write code that copies the a array to the b array.

31 III. Passing Arrays As Arguments to Methods To pass an array, we pass the value in the variable that references the array. It is passed just as an object is passed: The actual array itself is not passed, but the reference to the array is passed into the parameter. This means the method has direct access to the original array.

32 III. Passing Arrays As Arguments to Methods showArray(numbers); public static void showArray(int[] array) { for(int i = 0; i < array.length; i++) System.out.print(array[i] + “ “); } An array address

33

34

35 IV. Some Useful Array Algorithms and Operations 1. Comparing Arrays 2. Summing the Values in a Numeric Array 3. Getting the Average of the Values in a Numeric Array 4. Finding the Highest and Lowest Values in a Numeric Array 5. Partially Filled Arrays 6. Working with Arrays and Files

36 IV.1. Comparing Arrays To compare the contents of two arrays, we must compare the elements of the two arrays. We cannot use the == operator to compare two array reference variables and determine the arrays are equal. int[] firstArray = { 5, 10, 15 }; int[] secondArray = { 5, 10, 15}; if(firstArray == secondArray) //This is a mistake. System.out.println(“The arrays are the same.”); else System.out.println(“The arrays are not the same.”);

37 IV.1. Comparing Arrays Comparing the contents of two arrays: int[] firstArray = { 5, 10, 15 }; int[] secondArray = { 5, 10, 15}; boolean arrayEqual = true; //Flag variable int index = 0; //Loop control variable //First determine whether the arrays are the same size. if(firstArray.length == secondArray.length) arrayEqual = false; while(arrayEqual && index < firstArray.length) { if(firstArray[index] != secondArray[index]) arrayEqual = false; else index++; } if(arrayEqual) System.out.println(“The arrays are equal.”); else System.out.println(“The arrays are not equal.”);

38 IV.2. Summing the Values in a Numeric Array To sum the values in an array we must use a loop with an accumulator variable. The loop adds the value in each array element to the accumulator. int[] units = new int[5]; //.... int acc = 0; // Initialize accumulator for(int index = 0; index < units.length; index++) acc += units[index];

39 IV.3. Getting the Average of the Values in a Numeric Array The first step in calculating the average of all the values in an array is to sum the values. The second step is to divide the sum by the number of elements in the array. double[] scores = new double[10]; //.... double acc = 0; // Initialize accumulator double average; //Will hold the average for(int index = 0; index < scores.length; index++) acc += scores[index]; average = acc / scores.length;

40 IV.4. Finding the Highest and Lowest Values in a Numeric Array int[] numbers = new int[50]; //.... //Find the highest value int highest = numbers[0]; for(int index = 1; index highest) highest = numbers[index]; } How to find the lowest value ?

41 IV.5. Partially Filled Arrays Sometimes we need to store a series of items in an array, but we do not know the number of items that there are. One solution is to make the array large enough to hold the largest possible number of items. If the actual number of items stored in the array is less than the number of elements, the array will be only partially filled. When we process a partially filled array, we must only process the elements that contain valid data items. A partially filled array is normally used with an accompanying integer variable that holds the number of items stored in the array.

42 IV.6. Working with Arrays and Files Saving the contents of an array to a file is a straightforward procedure: Use a loop to step through each element of the array, writing its contents to the file. int[] numbers = { 10, 20, 30}; //Open the file FileWriter fwriter = new FileWriter(“Values.txt”); PrintWriter outputFile = new PrintWriter(fwriter); //Write the array elements to the file for(int index=0; index<numbers.length;index++) outputFile.println(numbers[index]); //Close the file outputFile.close();

43 IV.6. Working with Arrays and Files Open the file Values.txt and read its contents back into the numbers array: int[] number = new int[5]; String str;// To hold lines read from the file int index = 0; // Loop control variable //Open the file FileReader freader = new FileReader(“Values.txt”); BufferedReader inputFile = new BufferedReader(freader);

44 IV.6. Working with Arrays and Files //Read the file contents into the array str = inputFile.readLine(); while(str != null && index < numbers.length) { numbers[index] = Integer.parseInt(str); index++; str = inputFile.readLine(); } //Close the file inputFile.close();

45 V. Returning Arrays from Methods A method can return a reference to an array. The return type must be an array reference. public static double[] getArray() { double[] array = {1.2, 2.3, 4.5 }; return array; } Array reference

46 VI. The Sequential Search Algorithm A search algorithm is a method of locating a specific item in a large collection of data. The sequential search algorithm uses a loop to sequentially steps through an array: Starts with the first element. Compares each element with the value being searched for. Stops when the value is found or the end of the array is encountered. If the value being searched for is not in the array, the algorithm searched to the end of the array.

47

48