L EC. 05: A RRAYS 0. C ONTENT  Features of arrays  Declaring, creating and using arrays  Enhanced for -construct  Variable length parameter-list 1.

Slides:



Advertisements
Similar presentations
Arrays.
Advertisements

Arrays. A group of data with same type stored under one variable. It is assumed that elements in that group are ordered in series. In C# language arrays.
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.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
Chapter 9: Arrays and Strings
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
 Pearson Education, Inc. All rights reserved Arrays.
Multi-Dimensional Arrays in Java "If debugging is the process of removing software bugs, then programming must be the process of putting them in." -- Edsger.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Chapter 8 Arrays and Strings
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.
Arrays Part 9 dbg. Arrays An array is a fixed number of contiguous memory locations, all containing data of the same type, identified by one variable.
CMSC 202 Arrays. Aug 6, Introduction to Arrays An array is a data structure used to process a collection of data that is all of the same type –An.
ARRAYS 1 Week 2. Data Structures  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently 
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
 2005 Pearson Education, Inc. All rights reserved. 1 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.
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 8: Arrays.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
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.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Lecture 5: Arrays A way to organize data MIT AITI April 9th, 2005.
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.
ARRAYS Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Lecture 7 Introduction to Programming in C Arne Kutzner Hanyang University / Seoul Korea.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
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.
IN THE NAME OF ALLAH WHO IS THE MOST BENEFICENT AND MOST MERCIFUL.
Array Objectives To understand the concept of arrays To understand the purpose to which we use arrays. To be able to declare references to arrays. To be.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
Arrays.
IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Two Dimensional Arrays Found in chapter 8, Section 8.9.
Chapter 8: Part 3 Collections and Two-dimensional arrays.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
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];
Arrays in java Unit-1 Introduction to Java. Array There are situations where we might wish to store a group of similar type of values in a variable. Array.
Visual C# 2005 Using Arrays. Visual C# Objectives Declare an array and assign values to array elements Initialize an array Use subscripts to access.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
CSI 3125, Preliminaries, page 1 Arrays. CSI 3125, Preliminaries, page 2 Arrays Group of related typed variables that referred to a common name Each data.
 2005 Pearson Education, Inc. All rights reserved Arrays.
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.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Arrays Chapter 7.
Arrays Chapter 7.
Computer Programming BCT 1113
Array, Strings and Vectors
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.
EKT150 : Computer Programming
Object Oriented Programming in java
MSIS 655 Advanced Business Applications Programming
Data Structures (CS212D) Week # 2: Arrays.
Arrays Chapter 7.
Arrays Week 2.
Arrays.
Presentation transcript:

L EC. 05: A RRAYS 0

C ONTENT  Features of arrays  Declaring, creating and using arrays  Enhanced for -construct  Variable length parameter-list 1

A RRAYS  An array ( 陣列 ) is a contiguous memory space with fixed size used to store a group of data with compatible data type.  An array is the simplest and basic data structure ( 資料 結構 ) used to store one or more logical-related data.  An array can be used to store all the objects representing the students of a department.  An array can be used to store all the objects representing the employees of a company.  Arrays support random access ( 隨機存取 ). 2

A RRAYS IN J AVA  An array is a collection of variables of the compatible type, referred to by a common identifier.  Each individual variable is called an element ( 元素 ).  Java only supports one-dimensional arrays.  Java supports mechanism, called array-of-arrays, for building multi-dimensional arrays from one-dimensional arrays.  Arrays are used for a variety of purposes because they offer a convenient means of grouping together related variables.  Using an array to hold the records of all the students in a class.  Each array is an object.  The class of an array object is automatically created by Java platform. 3

D ECLARING ARRAYS  Syntax form for declaring an array []; or [] ;  The is the type of array elements, so called the base type.  Example  String strs[], addresses[], str; // str is not an array  int[] vector, score; // both vector and list are arrays  As arrays are objects in Java, the variables declared as arrays are reference variables referred to objects which represent arrays.  When an array is declared, the array is not created. 4

C REATING ARRAYS  An array is created by using the new operator with the following form. new [ ];  Example  new String[10]  new int[10*2]  The must be an int-expression representing the number of elements in the array.  The new operator dynamically allocates memory for an array and returns the reference of the array.  Array declaration and creation can be combined into a single statement.  String strs[] = new String[10];  The length of an array cannot be changed once it is created. 5

L ENGTH OF AN ARRAY  The length of an array is the number of data item can be stored in the array.  Each array has a instance field named length to represent the length of the array.  The length field is final.  A final field in Java is a field that can be set only once.  Setting the length field of an array is illegal.  Example  The output of the following segment is int vector[] = new int[10]; System.out.println(vector.length);

A CCESSING ARRAY ELEMENTS  Each individual element within an array is accessed by using an index( 索引 ).  An index describes the position of an element within an array.  In Java, all arrays have zero as the index of their first element.  This index style is called zero-index.  The type of indices must be compatible to int.  To access an array element, specify the index of the element you want, surrounded by square brackets.  Syntax form [ ]  Example  strs[0] = “Hello”;  vector[3] = vector[0] + vector[2]; 7

A CCESSING ARRAY ELEMENTS  The must be an int -expression.  The value of must be within the range [0, length – 1], where length is the number of elements in an array.  If the is out of bound, an exception (run-time error) occurs.  The best way to process array elements is to use the for - construct.  Example  Let nums be an int array, then the following segment can find the maximum and minimum elements in nums. int min, max; min = max = nums[0]; for(int i = 1; i < nums.length; i++) { if(min > nums[i]) min = nums[i]; if(max < nums[i]) max = nums[i]; } 8

I NITIALIZING ARRAYS  Syntax form 1 = { };  Syntax form 2 = new []{ };  The initializers are separated by using comma.  The length of an array is determined by the number of initializers.  The length cannot be specified if an initializer is given.  Example  String strs[] = {“hello”, “an”, “example”}; //legal  String strs[]; strs = {“hello”, “an”, “example”}; //illegal  int vector[] = new int[]{1, 2, 3, 4, 5, 6}; //legal  int vector[]; vector = new int[]{1, 2, 3, 4, 5, 6}; //legal 9

E XAMPLE OF PROCESSING ARRAYS : BUBBLE SORTING  Bubble sorting is a simple, but may not be efficient for large size arrays, sorting method.  Bubble sorting proceeds iteratively.  In the i th iteration  Comparing the adjacent pair of elements, starting from the right-most two elements, and swapping them if they are out of order  Stopping the iteration when the (i-1) th element is compared 10

F IGURE OF BUBBLE SORTING ( FIRST ITERATION ) 11

C LASS FOR SORTING class Sorting { public static int[] bubbleSort( int[] vector ) { // a class method int sorted[]; // declare an array sorted = new int[vector.length]; // create an array //duplicating vector to sorted System.arraycopy(vector, 0, sorted, 0, vector.length); for(int i = 1; i < sorted.length; i++) { for(int j = sorted.length – 1; j >= i; j--) { // ith iteration if(sorted[j–1] > sorted[j]) { //out of order, swap them int temp = sorted[j]; sorted[j] = sorted[j–1]; sorted[j–1] = temp; } return sorted; } 12

M ORE EFFICIENT VERSION 13 class Sorting { public static int[] bubbleSort( int[] vector ) { // a class method boolean flag; int sorted[]; // declare an array sorted = new int[vector.length]; // create an array //duplicating vector to sorted System.arraycopy(vector, 0, sorted, 0, vector.length); loop: for(int i = 1; i < sorted.length; i++) { // label it flag = true; for(int j = sorted.length – 1; j >= i; j--) { // ith iteration if(sorted[j–1] > sorted[j]) { //out of order, swap them flag = false; int temp = sorted[j]; sorted[j] = sorted[j–1]; sorted[j–1] = temp; } if(flag) break loop; // stop earlier } return sorted; }

M ULTIDIMENSIONAL ARRAYS  In Java, a multidimensional array is implemented by using the concept of array of arrays.  In a 2-dimensional array, i.e. a matrix( 矩陣 ), each row can be treated as a 1-dimensional array.  So, a 2-dimensional array with m rows can be treated as a set of m 1-dimensional arrays.  A 2-dimensional array can be implemented as a 1- dimensional array in which each element is a 1- dimensional array.  The concept for implementing 2-dimensional arrays can be easily extended to any n-dimensional arrays. 14

D ECLARING MULTIDIMENSIONAL ARRAYS  Syntax form [][]…[];  Example  String empSkill[][]; // a 2-dimensional array  int cube[][][]; // a 3-dimensional array 15

C REATING REGULAR MULTIDIMENSIONAL ARRAYS  Syntax form new [ ][ ]…[ ]  Example  empSkill = new String[10][2];  Cube = new int[8][4][10]; 16

C REATING IRREGULAR MULTIDIMENSIONAL ARRAYS  In Java, you can create upper-level arrays and then create lower-level arrays separately.  Before upper-level array is created, no lower-level array can be created.  Example 1 17 int matrix[][]; matrix = new int[3][]; // matrix = new int[][10]; is illegal matrix[0] = new int[4]; matrix[1] = new int[8]; matrix[2] = new int[6];

C REATING IRREGULAR MULTIDIMENSIONAL ARRAYS  Example 2 18 int cube[][][]; cube = new int[2][][]; //create one 1-dimensional array with 2 elements // cube = new int[2][][10]; is illegal cube[0] = new int[2][3]; // totally create 3 1-dimensional arrays cube[1] = new int[3][]; // create one 1-dimensional array with 3 elements cube[1][0] = new int[2]; // create one 1-dimensional array with 2 elements cube[1][1] = new int[3]; // create one 1-dimensional array with 3 elements Cube[1][2] = new int[2]; // create one 1-dimensional array with 2 elements

L ENGTH OF ARRAYS  Based on the examples on pages 17 and 18  matrix.length equals 3.  matrix[1].length equals 8.  matrix[1][0].length is illegal since matrix[1][0] is not an array.  cube.length equals 2.  cube[1].length equals 3.  cube[0][2].length equals 2.  Remember that. can access the instance field of an object pointed by a reference variable.  Since matrix and matrix[1] points to array objects, matrix.length and matrix[1].length read the lengths of array objects.  Since matrix[1][0] is int, matrix[1][0].length is illegal. 19

A CCESSING ELEMENTS OF MULTIDIMENSIONAL ARRAY  For multidimensional arrays, each dimension needs a separate index set.  To access an element of a multidimensional array, you need to specify the index for each dimension.  Syntax form [ ][ ]…[ ]  Example  matrix[0][0] = matrix[1][1] + matrix[2][1];  cube[0][1][2] = 3 * cube[2][1][0]; 20

I NITIALIZING MULTIDIMENSIONAL ARRAYS  A multidimensional array can be initialized by enclosing each dimension’s initializer list within its own set of curly braces.  Example 21 String empSkill[][] = { {“John”, “Mary”, “Ken”}, // for empSkill[0] {“Network”, “Security”, “OS”} // for empSkill[1] } int cube[][][] = { { {1}, // cube[0][0][0] is 1 {1, 2} // cube[0][1][0] is 1, cube[0][1][1] is 2 }, { {22, 21, 34}, // cube[1][0][0] is 22 {30, 1}, // cube[1][1][1] is 1 {85, 34, 22, 56} // cube[1][2][3] is 56 }

E XAMPLE OF USING 2- DIMENSIONAL ARRAYS : MANIPULATING MATRICES class Matrix { int matrix[][]; Matrix(int noRow, int noCol) { //constructor matrix = new int[noRow][noCol]; //create a 2-dim array to represent the matrix for(int i = 0; i < noRow; i++) { // initialize the matrix for(int j = 0; j < noCol; j++) { matrix[i][j] = 0; } Matrix(int[][] arr) { // convert a 2-dimensional array to a Matrix object matrix = new int[arr.length][]; for( int i = 0; i < arr.length; i++) { matrix[i] = new int[arr[i].length]; System.arraycopy(arr[i], 0, matrix[i],0, arr[i].length); // copy the ith row } public void setElement(int row, int col, int val) { matrix[row][col] = val; } public int getElement(int row, int col) { return matrix[row][col]; } 22

E XAMPLE OF USING 2- DIMENSIONAL ARRAYS : MANIPULATING MATRICES public void add(Matrix addend) { // add addend to this object for(int i = 0; i < matrix.length; i++) { for(int j = 0; j < matrix[i].length; j++) { matrix[i][j] += addend[i][j]; } public void printMatrix() { // print this object in matrix form for( int i = 0; i < matrix.length; i++) { for(int j = 0; j < matrix[i].length; j++) { System.out.print(matrix[i][j]+” “); } System.out.println(); } 23

F OR - EACH STYLE for - CONSTRUCT  Beginning with J2SDK v. 1.5, Java supports a new for-each style for -construct, so called enhanced for -construct.  The enhanced for -construct cycles through a collection of objects, such as an array, in strictly sequential fashion, from start to finish.  Syntax form for( : ) statement;  The specifies the type of.  The specifies the name of an iteration variable that will receive the elements from, one at a time, from beginning to end.  The collection being cycled through is specified by.  There are various types of collections, such as primitive and class types, that can be used with the for. 24

F OR - EACH STYLE for - CONSTRUCT  The base type of must be compatible with the type of iteration variable.  With each iteration of the loop, the next element in the collection is retrieved and stored in.  The loop repeats until all elements in the collection have been obtained.  Its iteration variable is “read-only” as it relates to the underlying array.  An assignment to the iteration variable has no effect on the underlying array.  Example  The following segment can add up all the data in a int array name nums. 25 int sum = 0; for(int var : nums) { sum += var; }

F OR - EACH STYLE for - CONSTRUCT  Since the type of can be arrays, the enhanced for -construct can also apply to process multidimensional arrays as the following example.  Example  Let matrix be a 2-dimensional array. 26 int sum = 0; for(int row[]: matrix) { for(int val : row) { sum += val; }