Chapter 6 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays and Classes l Sorting Arrays l Multidimensional Arrays ** ** multidimensional.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 7- 1 Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3.
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Arrays Chapter 6 Chapter 6.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
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.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
Chapter 9: Arrays and Strings
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
Chapter 9 Introduction to Arrays
Programming Logic and Design Fourth Edition, Comprehensive
Java Unit 9: Arrays Declaring and Processing Arrays.
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 10Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 10 l Array Basics l Arrays in Classes and Methods l Programming.
1 Week 9 l Array Basics l Arrays in Classes and Methods l Programming with Arrays and Classes l Sorting Arrays l Multidimensional Arrays Arrays.
Lecturer: Dr. AJ Bieszczad Chapter 6 COMP 150: Introduction to Object-Oriented Programming 6-1 l Array Basics l Arrays in Classes and Methods l Programming.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
Lists in Python.
1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming with Arrays and Classes l Sorting Arrays l Multidimensional Arrays Arrays.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
A First Book of ANSI C Fourth Edition
Chapter 8 Arrays and Strings
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
Chapter 10. Arrays Array Basics Arrays in Classes and Methods Programming with Arrays and Classes Sorting Arrays Computer Programming with JAVA.
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.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
ARRAYS Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall
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.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Chapter 11. Multidimensional Arrays and Vectors Multidimensional Arrays Vectors Computer Programming with JAVA.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
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.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
CSCI 3328 Object Oriented Programming in C# Chapter 7: Arrays 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX 78539
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
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.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Multidimensional Arrays l Vectors Multidimensional Arrays.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
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.
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 Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Chapter 9 Introduction to Arrays Fundamentals of Java.
Arrays Chap. 9 Storing Collections of Values 1. Introductory Example Problem: Teachers need to be able to compute a variety of grading statistics for.
Data Structures & Algorithms CHAPTER 2 Arrays Ms. Manal Al-Asmari.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Arrays Chapter 7.
EKT472: Object Oriented Programming
Arrays Chapter 6 Array Basics Arrays in Classes and Methods
Arrays.
Presentation transcript:

Chapter 6 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays and Classes l Sorting Arrays l Multidimensional Arrays ** ** multidimensional arrays will be further discussed in COMP123 Arrays

Chapter 6 2 What is an Array? l Array [in general programming] »a contiguous block of equally-sized memory blocks »each block is distinguished by an index, subscript, element number, or location value (all mean the same thing) »all array elements are of the same type (primitive or class) »allow multiple values to be [sort of] referenced by on name l Arrays [in Java] »are older programming structures (list switch/case) »for multi-value storage, you are encouraged to use the advanced Java classes: Lists, Collections, and Vectors l Arrays are treated like objects (reference variables), without the ADT complexity of being instances of classes

Chapter 6 3 Creating Arrays l General syntax for declaring an array: type[] array_name = new type[length]; l Examples: int[] heights; // array ref. var. (null array) heights = new int[22]; // array of 22 ints // array of 80 characters char[] symbol = new char[80]; // array of 100 double values double[] reading = new double[100]; // array of 15 Shape objects Shape[] geometries = new Shape[15];

Chapter 6 4 Three Position for [ ] (Brackets) when used with Arrays l declaration—to indicate that reference variable is a reference to an array of a specific type »create an int array variable, but not an array! »int[] pressure; l creating (allocating in memory) a new array »pressure = new int[100]; »int[] levels = new int[10]; l indexing a specific element within an array »levels[3] = SavitchIn.readLineInt(); »System.out.print("4th elem."+levels[3]);

Chapter 6 5 Array Terminology temperature[n + 2] temperature[n + 2] = 32; array name: temperature index (also called a subscript, location, or element number) - must be an int, - or an expression that evaluates to an int indexed variable (also called element) - holds the value at the index position The term "element" is usually interchangeable with the terms: index, array value, element location, and "array thing at index" data value of the indexed variable - also called an element of the array

Chapter 6 6 Array Length l length of an array defined during the: new type[length] statement »determines the number of equally-size data blocks allocated for the array elements »memory locations are allocated, whether or not elements are explicitly given values array length is stored the instance variable length, Species[] entry = new Species[20]; System.out.println( entry.length ); // shows: 20 l array length is established during the new and cannot be changed »although the array reference variable can be "pointed to" a new memory address that identifies another array of smaller, or larger, length! (more on this later)

Chapter 6 7 Initializing an Array during Declaration l arrays can be initialised during declaration with a comma- separated list in braces l non- initialised elements are assigned the default value, »0 for numeric arrays, an activated constructor for objects »if only the list is provided, the array is of that length l example: double[] reading = {5.1, 3.02, 9.65}; System.out.println( reading.length ); -displays "3", since array reading has values: [0] = 5.1 [1] = 3.02 [2] = 9.65

Chapter 6 8 Subscript Range l array indexes (subscripts) begin at [0] and proceed to [array length-1] »this is similar to character positions in String objects, since String objects use characters arrays to store data int[] scores = {97, 86, 92, 71}; –in place of, int[] scores = new int[4]; scores[0] = 97; scores[1] = 86; scores[2] = 92; scores[3] = 71; l *** if reference is made beyond the [length-1] index, this generates a run-time error: "array subscript out of range" »Java is "array safe"—in C/C++, no error is reported!

Chapter 6 9 Initializing Array Elements with a Loop l since arrays are contiguous and of an unchanging size, a for loop is commonly used l array elements of numeric type are initialised to zero (0) during declaration –elements of class type are initialised to null –it is always good to initialise an newly declared array—why? l example: int i; //loop counter/array index int[] a = new int[10]; // 10 elem. int array for(i=0; i<a.length; i++) // loop: 0..9 a[i] = 0; // init. to 0

Chapter 6 10 Some things to do with arrays l setting element values to result of method call: for (int i=0; i<ray.length; i++) { System.out.print("Enter value "+i+":"); ray[i] = SavitchIn.readLineInt(); } l summing values in an array: for (int i=0; i<ray.length; i++) sum = sum + ray[i]; l copy one array to another (both of equal length) : for (int i=0; i<array.length; i++) brray[i] = array[i]; l reverse copy of one array to another (both of equal length) : for (int i=0; i<array.length; i++) { upperindex = (array.length-1)-i brray[i] = array[upperindex]; } or for (int i=0, k=array.length-1; i<array.length; i++, k--) brray[i] = array[k];

Chapter 6 11 Some things to do with arrays l determine the minimum and maximum values within an array double min=ray[0], // init. both min and max max=ray[0]; // to the first element value for (int i=1; i<ray.length; i++) { if (ray[i] < min) // if current element < min min = ray[i]; // set min to current element if (ray[i] > max) // if current element > max max = ray[i]; // set max to current element } l for the above, could the second if be changed to else if ? l search for the first occurrence of a value & remember location: int loc = 0; // init. loc to first position for(loc=0; ((loc<ray.length) && (ray[loc]!=searchval)); loc++); // after, if loc is < ray.length, item found at loc // if loc is = ray.length, item not found

Chapter 6 12 Some things to do with arrays l check to see if two arrays are equal (same order of values): boolean equal=true; // assume they are equal for (int i=0; i<array.length; i++) { if (array[i] != brray[i]) // check if != { equal = false; // set false break; // stop loop } or boolean equal=true; // assume they are equal for (int i=0; equal ; i++) // loop while equal equal = (array[i] == brray[i]); // check equality

Chapter 6 13 Arrays and Array Elements as Method Arguments l arrays, and the individual array elements, can be used with classes and methods just like other primitive variable and objects »both an indexed element and the array identifier can be legally used as argument in a method call l through a return statement, methods can return a single array element value, or an array identifier l BUT DO NOT CONFUSE THE ARRAY WITH ITS ELEMENTS!!! »double[] list = new list[100]; »list is not the same as list[2] !!! »list is an array reference, list[2] is a double variable value

Chapter 6 14 Array Names as Method Arguments l arrays are similar to objects: the array is a reference variable l arrays arguments given to methods are pass-by-reference »only the memory address is passed to the method »changes to the array in the method, change the original values public static void getArray (int[] array) { for(int i = 0; i < array.length; i++) array[i] = inputInt("Enter value "+(i+1)); }// end of getArray() public static void showArray (int[] array) { for(int i = 0; i < array.length; i++) print( array[i] ); }// end of showArray()

Chapter 6 15 Checking Arrays for Equality…in a Method same technique as previous, except now using a method (remember: arrays must be of equal length) public static boolean arrayEquals (double[] a, double[] b) { boolean equal=true; // assume they are equal for (int i=0; i<a.length; i++) if (a[i] != b[i]) // check if != { equal = false; // set false break; // stop loop } return (equal); // return equality status }// end of arrayEquals()

Chapter 6 16 Methods that Return an Array l an array is not passed in, but the address of the array is passed back l the local array name c (in main() ) is assigned the address which is returned from the call to vowels() l the local array in vowels(), newarray, is lost when the methods finishes but the address is returned and stored l Java reused memory only when nothing points to it! c, newArray, and the return type of vowels are all the same type: array of char

Chapter 6 17 Partially Filled Arrays l sometimes only part of an array contains useful data –consider an array of maximum 100 marks, but there are only 30 students in the class l array elements always contain a value (random or otherwise) l a partially-filled array is a standard array, except that an int is declared to describe the number of used array elements l example: double[] quizzes = double [100]; // 100 quizzes int num_quizzes = 0; // hold # of quizzes

Chapter 6 18 Example of a Partially Filled Array quizzes[0]10.5 quizzes[1]20.0 quizzes[2]18.5 quizzes[3] quizzes[4] num_quizzes - 1 unused values num_quizzes will have a value of 3 quizzes.length will have a value of 5

Chapter 6 19 Sorting an Array l sorting a list of elements is a common task with arrays –sort values in ascending order (1,2,4,10,12,20,...) –sort values in descending order (20,12,10,4,2,1,...) –sort strings in alphabetic order ("Bob", "Chuck", "Erin",...) l there are many techniques used in sorting »bubble sort, selection sort, shell sort, binary sort, quick sort, … l Selection sort (page 423) »easy to understand and program, although not efficient l Bubble sort (not in text) »also easy to understand and program, very inefficient "the more efficient a sort technique is, the more difficult it is to understand!"

Chapter 6 20 Bubble Sort Algorithm l this technique processes an array multiple times and "percolates" (or bubbles) the largest value to the end of the array –"largest to end"—ascending; "smallest to end"—descending –problem with bubble sort: it performs unnecessary sorts l the algorithm (ascending sort): 1. assume the array is filled with out of order element values 2. loop a counter i from the last element index down to 1 (i essentially works down the list, placing the largest at end) 2.1 loop a counter j from 0 up to i (j essentially works up the "unsorted" elements, pushing elements up) if current element (at [j]) is greater than next (at [j+1]) swap the element values between [j] and [j+1] 3. end of sort, elements are now in sorted order

Chapter 6 21 public void bubblesort (int[] ray) { for (int i=ray.length-1; i>=1; i--) // loop last index down to 1 for (int j=0; j<i; j++) // loop 0 up to ith element if (ray[j] > ray[j+1]) // if cur. (j) > next (j+1), then swap (ray, j, j+1) // swap element, put in correct order // nothing to return, since the array is call-by-reference }// end of bubblesort() public void swap (int array[], int pos1, int pos2) { int t; // internal dummary/temporary variable t = array[pos1]; // store pos1 to t array[pos1] = array[pos2]; // store pos2 to pos1 array[pos2] = t; // store t to pos2 }// end of swap() l of course, whether the methods are public static void, or public void, or private void, depends on whether they are –in a program class or utility class –public methods in a proper class, or –private methods used only within a class

Chapter 6 22 Multidimensional Arrays l arrays with more than one index »number of dimensions = number of indexes l arrays with more than two dimensions are a simple extension of two-dimensional (2D) arrays l a 2D array corresponds to a table or grid »one dimension is the row »the other dimension is the column »cell: an intersection of a row and column »an array element corresponds to a cell in the table l 2D arrays are actually, 1D arrays in which each element is simply another 1D!

Chapter 6 23 Table as a 2-Dimensional Array l The table assumes a starting balance of $1000 l First dimension: row identifier - Year l Second dimension: column identifier - percentage l Cell contains balance for the year (row) and percentage (column) l Balance for year 4, rate 7.00% = $

Table as a 2-D Array l Generalizing to two indexes: [row][column] l First dimension: row index l Second dimension: column index l Cell contains balance for the year/row and percentage/column l All indexes use zero-numbering »Balance[3][4] = cell in 4th row (year = 4) and 5th column (7.50%) »Balance[3][4] = $1311 (shown in yellow) 24 Row Index 3 (4th row) Column Index 4 (5th column)

Chapter 6 25 Java Code to Create a 2-D Array l Syntax for 2-D arrays is similar to 1-D arrays Declare a 2-D array of int s named table »the table should have ten rows and six columns int[][] table = new int[10][6];

Chapter 6 26 Method to Calculate the Cell Values Each array element corresponds to the balance for a specific number of years and a specific interest rate (assuming a starting balance of $1000): balance(starting, years, rate) = (starting) x (1 + rate) years The repeated multiplication by (1 + rate) can be done in a for loop that repeats years times. balance method in class InterestTable

Chapter 6 27 Processing a 2-D Array: for Loops Nested 2-Deep Arrays and for loops are a natural fit To process all elements of an n -D array nest n for loops »each loop has its own counter that corresponds to an index l For example: calculate and enter balances in the interest table »inner loop repeats 6 times (six rates) for every outer loop iteration »the outer loop repeats 10 times (10 different values of years ) »so the inner repeats 10 x 6 = 60 times = # cells in table Excerpt from main() of InterestTable

Chapter 6 28 Multidimensional Array Parameters and Returned Values l Methods may have multi-D array parameters l Methods may return a multi-D array as the value returned l The situation is similar to 1-D arrays, but with more brackets Example: a 2-D int array as a method argument Notice how the number of columns is obtained Notice how the number of rows is obtained showTable method from class InterestTable2

Chapter 6 29 Ragged Arrays l Ragged arrays have rows of unequal length »each row has a different number of columns, or entries l Ragged arrays are allowed in Java Example: create a 2-D int array named b with 5 elements in the first row, 7 in the second row, and 4 in the third row: int[][] b; b = new int[3][]; b[0] = new int[5]; b[1] = new int[7]; b[2] = new int[4];

Chapter 6 30 Summary Part 1 l An array may be thought of as a collection of variables, all of the same type. l An array is also may be thought of as a single object with a large composite value of all the elements of the array. Arrays are objects created with new in a manner similar to objects discussed previously.

Chapter 6 31 Summary Part 2 l Array indexes use zero-numbering: »they start at 0, so index i refers to the (i+1)th element; »index of the last element: (length-of-the-array - 1) »Any index value outside the valid range of 0 to length-1 will cause an array index out of bounds error when the program runs. l A method may return an array. l A "partially filled array" is one in which values are stored in an initial segment of the array: »use an int variable to keep track of how many variables are stored.

Chapter 6 32 Summary Part 3 l An array indexed variable can be used as an argument to a method anyplace the base type is allowed: »if the base type is a primitive type then the method cannot change the value of the indexed variable; »but if the base type is a class, then the method can change the value of the indexed variable. l When you want to store two or more different values (possibly of different data types) for each index of an array, you can use parallel arrays (multiple arrays of the same length). l An accessor method that returns an array corresponding to a private instance variable of an array type should be careful to return a copy of the array, and not return the private instance variable itself. l The selection sort algorithm can be used to sort an array of numbers into increasing or decreasing order.

Chapter 6 33 Summary Part 4 l Arrays can have more than one index. l Each index is called a dimension. l Hence, multidimensional arrays have multiple indexes, »e.g. an array with two indexes is a two-dimensional array. l A two-dimensional array can be thought of as a grid or table with rows and columns: »one index is for the row, the other for the column. l Multidimensional arrays in Java are implemented as arrays of arrays, »e.g. a two-dimensional array is a one-dimensional array of one-dimensional arrays.