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.

Slides:



Advertisements
Similar presentations
Arrays.
Advertisements

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 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.
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
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.
1 Introduction to Arrays Problem: –Input 5 scores, compute total, average –Input Example –test scores,employees,temperatures.
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 8 Arrays and Strings
7. Arrays. Topics Declaring and Using Arrays Some Array Algorithms Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList.
Arrays Chapter 7. 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores : Inspecting.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
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
Chapter 8: Arrays.
ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
Chapter 9: Arrays J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second Edition.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
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.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
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.
Week # 2: Arrays.  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently  Types of data.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
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.
Arrays.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Arrays An array is an indexed data structure which is used to store data elements of the same data type. An array is an indexed data structure which is.
Two Dimensional Arrays Found in chapter 8, Section 8.9.
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.
Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.
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.
C++ Array 1. C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used.
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.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
Chapter 9 Arrays. Chapter Objectives Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning of “array index.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Chapter 9 Introduction to Arrays Fundamentals of Java.
KUKUM-06/07 EKT120: Computer Programming 1 Week 6 Arrays-Part 1.
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.
Chapter 8: Arrays Starting Out with C++ Early Objects Ninth Edition
Computer Programming BCT 1113
Arrays … The Sequel Applications and Extensions
Chapter 8 Slides from GaddisText
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.
Lecture 9 Objectives Learn about arrays.
Data Structures (CS212D) Week # 2: Arrays.
Arrays Chapter 7.
Java Programming: Program Design Including Data Structures
Arrays.
Presentation transcript:

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 a type that: Stores a collection of individual components The whole collection has just one variable name Allows individual components from the collection to be stored and retrieved

2 Array structured collection of components (called array elements) all elements are of the same data type Array has one single name Array elements stored in adjacent memory locations. access individual components by using the array name together with index in square brackets The index indicates the position of the component within the collection.

3 Declaring an array: step 1. dataType[] arrayName; step 2. arrayName = new dataType[size]; dataType - type of data stored in each component of the array –int, float, char, etc arrayName - the name of the array An array is an object, arrayName is a reference variable size - number of components/members in the array –Integer expression,must have a value > 0. –can be a variable int[] scores; scores = new int[10];

Declaring an array: (two steps combined) dataType[] arrayName = new dataType[intExp]; int [] scores = new int[10]; Initializes its components to their default values Numeric arrays are initialized to 0 4

Zero-Equivalent Auto-Initialization Values TypeValue int0 double0.0 char‘\0’ booleanfalse objectsnull 5

6 int[] scores = new int[10]; scores

Specifying Array Size during Program Execution int arraySize; System.out.println(“Enter the size of the array: “); arraySize = console.nextInt(); int[] scores = new int[arraySize]; 7

8 Accessing Array Components arrayName[indexExp] indexExp – nonnegative integer reference array elements by using the subscript or the index [] – array subscripting operator Zero based indexing

Accessing Array Components new int[n] => subscripts 0 thru n-1 int scores[10] –scores[0] - is the first element of array test –scores[9] - last element of test –scores[10] = 1000; //writes beyond array-Exception scores[4] = 88; 9

10 Valid subscripts => can use variables, expression, or constant as subscripts scores[0] = 95; scores[i+2] = scores[i] + scores[i + 1]; x = scores[i]; System.out.println(scores[i * 2] );

11 Each array element is treated exactly as a variable buf[5] = 30; scores[1]++; i = buf[8] * 92; System.out.println(buff[80]); if (a[i] < 14) scores[3] = console.nextInt();

12 Array Initialization during Declaration by declaration –int[] age = {23, 34, 18, 44, 50 }; –double[] temps = {0.0, , 98.6}; –compiler will allocate space for each initialized item –new is not required here

length You can use the built-in length property to determine the size of any array. System.out.println(anArray.length); –will print the array's size length contains the size of the array int[] list = {10,20,30,40,50,60}; list.length is 6 13

Array traversal Processing each array sequentially from the first to the last for (int i = 0; i.length; i++) ; 14

Array limitations You can’t: change the size of an array in the middle of program execution (ArrayList class) compare arrays for equality using == print an array with System.out.println(arrayName); 15

16 Initializing an array to a specific value double[] sales = new double[10]; for (int index = 0; index < sales.length; index++) sales[index] = 10.00;

17 Input data into an array double[] sales = new double[10]; for (int index = 0; index < sales.length; index++) { Sysmt.out.println(“Enter value”); sales[index] = console.nextDouble(); }

18 Printing an array double[] sales = new double[10]; for (int index = 0; index < sales.length; index++) System.out.println(sales[index]);

19 Printing an array System.out.println(Arrays.toString(list)); Yields: [17, -3, 42, 8, 12, 2, 103]

20 Finding the sum and average of an array double[] sales = new double[10]; double Sum = 0; for (int index = 0; index < sales.length; index++) sum += sales[index]; double avg = sum/sales.length;

21 Determining the largest element of an array double[] sales = new double[10]; int maxIndex = 0; for (int index = 1; index < sales.length; index++) if (sales[maxIndex] < sales[index]) maxIndex = index; double largest = sales[maxIndex];

22 Printing an array in reverse order double[] sales = new double[10]; for (int index = sales.length - 1; index >= 0; index--) System.out.println(sales[index];

Array Index out of Bounds Exception double[] num = new double [10]; int i;//[i] can be 0,1, 2, 3, 4, 5, 6, 7, 8, 9 index out of bounds: i 9 ArrayIndexOutOfBoundsException for (int i = 0; i <= 10; i++) num[i] = 0; 23

Methods: Arrays as Formal Parameters: datatype[] arrayName Size not necessary Because arrays are reference variables, the array can be changed public static void processArrays(int[] listA, double[] listB) 24

Arrays as Actual Parameters: pass name of array in call method(arrayName); formal: public static void processArrays (int[] listA, double[] listB); actual: int[] intList = new int[10]; double[] doubleList = new double[15]; processArrays(intList,doubleList); 25

26 Method: print an array public static void printArray(int[] list) { for (int index = 0; index < list.length; index++) System.out.println(list[index]); }

27 Method: read an array public static void readArray(int[] list) { for (int index = 0; index < list.length; index++) { System.out.println(“Enter value”); list[index] = console.nextInt(); }

28 Method: read an array public static int readArray(int[] list, Scanner infile) { index = 0; while (infile.hasNext() && index < list.length) { list[index] = infile.nextInt(); index++; } return index; // number of elements read }

29 Method: read an array public static int[] readArray() { for (int index = 0; index < list.length; index++) { System.out.println(“Enter value”); list[index] = console.nextInt(); } return list; }

30 Method: sum an array public static int sumArray(int[] list) { int sum = 0; for (int index = 0; index < list.length; index++) sum += list[index]; return sum; }

31 Method: return index of largest element public static int indexLargestElement(int[] list) { int maxIndex = 0; for (int index = 1; index < list.length; index++) if (list[index] > list[maxIndex]) maxIndex = index; return maxIndex; }

32 Method: copy array public static void copyArray(int[] list1, int[] list2) { for (int index = 0; index < list.length; index++) list2[index] = list1[index]; }

Arrays as parameters to methods static final int ARRAY_SIZE = 10; int[] listA = new int[ARRAY_SIZE]; int[] listB = new int[ARRAY_SIZE]; printArray(listA); readArray(listA); copyArray(listA,listB); printArray(listA); printArray(listB); 33

Passing an array arrayName  base address arrayName  address of arrayName[0] When you pass an array as a parameter, the base address of the actual array is passed to the formal parameter 34

35 Linear Search public static int find(int[] list, int searchItem) { for (int ix = 0; ix < list.length(); ix++) { if (list[i] == searchItem) return ix; } return -1; }

36 Linear Search (also called Sequential Search) public static boolean find(int[] list, int searchItem) { int ix = 0; boolean found = false; while (!found && ix < list.length) { if (list[ix] == searchItem) found = true; else ix++ } return found; }

37 BINARY SEARCH requires sorted list – (Ex: phone books, dictionaries). keep dividing list in half, compare against middle argument eliminates one half of the elements after each comparison. efficient

38 Binary Search public static int binSearch(int[] list, int searchItem) { int first = 0; // lower bound on list int last = length - 1; // upper bound on list int middle; // middle index boolean found = false; while (!found && last >= first) { middle = (first + last)/2; if (item < list[middle] last = middle - 1; else if (item > list[middle]) first = middle + 1; else found = true; } if (!found) return -1; return middle; }

39 Average Number of Iterations

For-Each Loop Java 5: Enhanced for loop for ( : ) statement for (int index = 0; index < list.length; index++) System.out.println(list[index]); for (int index: list) System.out.println(index); Usually only applicable for examining each value in sequence 40

41 Caution using arrays with = arrayA = arrayB; both will refer to same array Shallow copy use the for loop for a deep copy

42 Caution using arrays with == if(arrayA == arrayB) –Returns true if they refer to the same array –arrays.equals provided if (arrays.equals(list1, list2)) System.out.println(“The arrays are equal”);

Comparing two 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) … 43

Parallel Arrays Two or more arrays Corresponding components hold related information int[] studentId = new int[50]; char[] courseGrade = new char[50]; int numStudents = 0; while (infile.hasNext() && numStudents < 50) { students[numStudents] = infile.nextInt (); courseGrade[numStudents] = infile.next().charAt(0); numStudents++; } 44

Array of String objects String[] nameList = new String[5]; nameList[0] = “Joe Smith”; … Use for loop to output nameList –for (int I = 0; I < nameList.length;i++) System.out.println(namelist[i] ); Also use String methods –nameList[4].substring(0,3) 45

Command line arguments public static void main(String[] args) Java DoSomething Java DoSomething temps.txt temps.out args[0] = “temps.txt” args[1] = “temps.out” 46

47 Two Dimensional Arrays table with rows and columns all items of the same data type access by row and column indices Example: tables or graphs

Declaring a two-dimensional array dataType[][] arrayName arrayName = new dataType[intExp1][intExp2]; dataType[][] arrayName = new dataType[intExp1][intExp2]; 48

49 int[][] A= new int[3][4];

50

51 int A[3][4] Virtually Stored A[0][0] A[0][1] A[0][2] A[0][3] A[1][0] A[1][1] A[1][2] A[1][3] A[2][0] A[2][1] A[2][2] A[2][3]

Accessing Array Components arrayName[indexExp1][indexExp2] A[2][3] = 25; Indices can be variables –A[i][j] 52

Two-dimensional arrays and the instance variable length Length can be used for number of rows and columns int[] matrix = new int[20][15]; Number of rows = matrix.length is 20 Number of columns - matrix[0].length is 15 53

Two dimensional arrays: special cases Can have different number of columns for each row int[][] board; board = new int[5]; //board.length is 5 board[0] = new int[6]; // board[0].length is 6 board[1] = new int[2]; board[2] = new int[5]; board[3] = new int[3]; board[4] = new int[4]; 54

Two-dimensional array initialization during declaration Elements of each row are enclosed within braces and separated by commas All rows are enclosed in braces int[][] board1 = { {2, 3, 1}, {15, 25, 13}, {20, 4, 7}, {11, 18, 14}}; int[][] board2 = { {2, 3, 1, 5}, {15, 25}, {11, 18, 10}}; 55

Initialize two-dimensional arrays: int[][] matrix = new int[ROWS][COLS]; for (int row = 0; row < matrix.length; row++) for (col = 0; col < matrix[row].length; col++) matrix[row][col] = 10; 56

Print two-dimensional arrays int[][] matrix = new int[ROWS][COLS]; for (int row = 0; row < matrix.length; row++) for (col = 0; col < matrix[row].length; col++) System.out.printf(“%7d”,matrix[row][col]) System.out.println(); 57

Input two-dimensional arrays int[][] matrix = new int[ROWS][COLS]; for (int row = 0; row < matrix.length; row++) for (col = 0; col < matrix[row].length; col++) matrix[row][col] = console.nextInt(); 58

Sum by row: two-dimensional arrays int[][] matrix = new int[ROWS][COLS]; for (int row = 0; row < matrix.length; row++) { sum = 0; for (col = 0; col < matrix[row].length; col++) sum += matrix[row][col]; System.out.println(“The sum of the elements of row “ (row +1) + “ = “ + sum); } 59

Sum by column: two- dimensional arrays int[][] matrix = new int[ROWS][COLS]; for (int col = 0; col < matrix[0].length; col++) { sum = 0; for (row = 0; row < matrix.length; row++) sum += matrix[row][col]; System.out.println(“The sum of the elements of column “ (col +1) + “ = “ + sum); } 60

61 Passing Two-Dimensional Arrays as Parameters public static void printMatrix(int[][] matrix) { for (int row = 0; row < matrix.length; row++) for (col = 0; col < matrix[row].length; col++) System.out.printf(“%7d”,matrix[row][col]) System.out.println(); } Call: printMatrix(board)

62 Multidimensional arrays arrays can have any number of dimensions –dataType[][]..[] arrayName = new dataType[intExp1][intExp2]..[intRxpn]; To access: –arrayName[indexExp1][indexExp2][indexExpn] Requires multiple loops to process

63 Multidimensional arrays Example: double [][][] graph = new double[30][30][30]; graph[3][2][5] = 27.68;