1 Arrays An array is a collection of data values, all of which have the same type. The size of the array is fixed at creation. To refer to specific values.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Kernighan/Ritchie: Kelley/Pohl:
Arrays. Topics Tables of Data Arrays – Single Dimensional Parsing a String into Multiple Tokens Arrays - Multi-dimensional.
CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
1 Fall 2009ACS-1903 Methods – Ch 5 A design technique referred to as stepwise refinement (or divide and conquer, or functional decomposition) is used to.
Chapter 10.
Road Map Introduction to object oriented programming. Classes
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Loops Notes adapted from Dr. Flores. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while”
1 Chapter 7 User-Defined Methods Java Programming from Thomson Course Tech, adopted by kcluk.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
© The McGraw-Hill Companies, 2006 Chapter 5 Arrays.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
C++ for Engineers and Scientists Third Edition
Chapter 7: User-Defined Methods
COMP 110 Introduction to Programming Mr. Joshua Stough September 10, 2007.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
Introduction to Methods
CSC 142 J 1 CSC 142 Arrays [Reading: chapter 10].
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Java Unit 9: Arrays Declaring and Processing Arrays.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
 2006 Pearson Education, Inc. All rights reserved Arrays.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Array Processing - 2. Objectives Demonstrate a swap. Demonstrate a linear search of an unsorted array Demonstrate how to search an array for a high value.
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.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
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.
Java Script: Arrays (Chapter 11 in [2]). 2 Outline Introduction Introduction Arrays Arrays Declaring and Allocating Arrays Declaring and Allocating Arrays.
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 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.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
August 6, 2009 Data Types, Variables, and Arrays.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
ITI 1120 Lab #5 Contributors: S. Boyd, R. Plesa, A. Felty, D. Inkpen, A. Williams, D. Amyot.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
CSE 110 Review Session Hans Hovanitz, Kate Kincade, and Ian Nall.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
How do you do the following? Find the number of scores within 3 points of the average of 10 scores? What kind of a tool do you need? Today’s notes: Include.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
int [] scores = new int [10];
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 Chap. 9 Storing Collections of Values 1. Introductory Example Problem: Teachers need to be able to compute a variety of grading statistics for.
ITM 3521 ITM 352 Functions. ITM 3522 Functions  A function is a named block of code (i.e. within {}'s) that performs a specific set of statements  It.
Data Structures & Algorithms CHAPTER 2 Arrays Ms. Manal Al-Asmari.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Chapter 7 User-Defined Methods.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
Chapter 6: User-Defined Functions I
User-Defined Functions
Lecture 4B More Repetition Richard Gesick
Chapter 3 Introduction to Classes, Objects Methods and Strings
7 Arrays.
int [] scores = new int [10];
CHAPTER 6 GENERAL-PURPOSE METHODS
Lecture 5: For Loops Building Java Programs: A Back to Basics Approach
int [] scores = new int [10];
Chapter 6: User-Defined Functions I
7 Arrays.
Java Programming Language
Classes, Objects and Methods
CS 1054: Lecture 2, Chapter 1 Objects and Classes.
Presentation transcript:

1 Arrays An array is a collection of data values, all of which have the same type. The size of the array is fixed at creation. To refer to specific values within the array, an array index is used to refer to a specific position in the array. –In Java, for an array of length n, the values in the array are indexed from 0 up to n – 1. Notation: a refers to the entire collection a[i] refers to the value at index i

2 length: 6 Arrays A has length 6 A[4] is 14 If i is 3, then A[i] is -2 Assign a value: A[5] = 6; A

3 Arrays in Java An array variable is declared with the type of the members. –For instance, the following is a declaration of a variable of an array with members of the type double: double[] anArray; When an array variable is declared, the array is NOT created. What we have is only a name of an array. –anArray will have the special value null until it is created.

4 Creating an array To create the array, operator new is used. We must provide the number of members in the array, and the type of the members. These cannot be changed later. double[] anArray; anArray = new double[5]; or, combining the declaration and the array creation: double[] anArray = new double[5]; When an array is created, the number of positions available in the array can be accessed using a field called length with the dot operator. For instance, anArray.length has a value 5.

5 Array creation double[] anArray ; anArray: null anArray = new double[3] anArray: ??? length Here, the array is not defined. Here, the array is defined, but the elements in the array are NOT defined.

6 Accessing array members Array members are accessed by indices using the subscript operator []. The indices are integers starting from 0. For instance, if anArray is an array of three integers, then: –the first member is anArray[0] –the second member is anArray[1], –and the third member is anArray[2]. The indices can be any expression that has an integer value. –If an index is out of range, i.e., less than 0 or greater than length-1, a run-time error occurs.

7 Initializing array members Array members can be initialized individually using the indices and the subscript operator. int [] intArray = new int[3]; intArray[0] = 3; intArray[1] = 5; intArray[2] = 4; Array members may also be initialized when the array is created: int [] intArray; intArray = new int [] { 3, 5, 4 };

8 Partial initialization of an Array An array may be partially initialized. int [] intArray = new int [5]; intArray[0] = 3; intArray[1] = 5; intArray[2] = 4; –In this case, intArray[3] and intArray[4] are undefined. When an array is processed, we may need another variable (or variables) to keep track of the indices for which we have assigned values.

9 Reference Types An array type is a reference type, because of the “pointer” to the array. It is important to distinguish the reference (pointer) from the “item being pointed to”. –In the diagram below, A is the reference, and the array is what is being pointed to. Java does not allow us to peek inside A to see what is in the pointer. A 5217 length A

10 Reference Types What happens with assignment and comparison of reference types? –It is the references that are compared or assigned, not the arrays. 03 length 2 A == B is true A B A B A == B is false 03 length

11 Reference Types Assignment only copies a reference, not the object to which is points. How can we make a copy of an array? B = A results in: A B NOT: A B 03 length

12 Lost references With reference types, be careful that you don’t “lose” the item to which a reference points. After the assignment, there is no reference to the second array. The second array will be forgotten by Java and cannot be recovered. BEFORE B = A A B 03 length AFTER B = A A B 03 length

13 Example: Find maximum, minimum array values

14 Example: Find maximum, minimum array values Strategy: –Use variables max and min to store our current known maximum and minimum values –Start with array position 0, and assume that this value is both the maximum and minimum. –Go through each of the remaining array positions, and do the following: Check if the value at the current array position is larger than the current maximum. –If so, replace the current maximum with the value at the current array position Check if the value at the current array position is larger than the current minimum. –If so, replace the current minimum with the value at the current array position

15 Example: Find position of maximum and minimum in an array A modification of the previous problem is to find the location of the maximum and minimum values As we loop through the array, we need to save both the maximum (and minimum) values AND their positions

16 Methods A method is a separate piece of code that can be called independently and/or repeatedly. Used to partition programs into smaller portions, each of which performs a well-defined function. We’ve already been using methods from the Math, Keyboard. –Now, we will create our own methods

17 Method calls When one method calls another: –The method that is currently executing stops and waits at the point of the call. –Values may be “passed” to the called method. –The called method executes. –When the called method finishes, a value may be passed back to the calling method. –The calling method restarts and continues // Statement 1 // Call method A // Statement 3 // Method A // Statement A1 // Statement A2 // return

18 Components of Methods Each method will have (optional except where noted): –name (required): used to identify method –parameters: values that must be supplied to method by caller –return value: one value returned by the method –local variables: variables used inside the method, and not accessible outside the method –body (required): code that performs the desired function

19 Example Horizontal motion under constant velocity Values that must be supplied to method: –x 0 (initial position), v 0 (initial velocity), t (time) Value the method must return to caller: –x (position of object at time t )

20 Method headers Here is the distance method: public static double findDistance( double x0, double v0, double t) { double x;// a local variable x = x0 + v0 * t; return x;// the value of x is returned to the caller } Here is a call to the distance method: double aDistance; aDistance = findDistance( 3.0, 4.0, 7.0 ); System.out.println("The distance is " + aDistance ); After this call, aDistance would have the value 31.0

21 Method headers public static double findDistance( double x0, double v0, double t) Header information –public : Accessibility: method can be called from any location in program –static : to be explained later –double : type of return value –findDistance : name of method –double x0, double v0, double t : ordered list of parameters, and their types:

22 A method with return type void If a method does not return a value, the return type should be void. A call activates the method to do whatever it is supposed to do. public static void print3(int x, int y, int z) { System.out.println("This method does not return any value."); System.out.println(x); System.out.println(y); System.out.println(z); } When the method is called by print3(3, 5, 7); it simply prints these arguments to the screen.

23 Variables in methods Parameter variables: –Declared in method header –Value from calling method is copied into parameter variable as method is called. –Variables are usable within the method only. Local variables –Declared within method body –Need to be explicitly initialized –Usable within the method only. When a method has completed, both parameter and local variables lose their values.

24 Variable duration and scope Duration: the “lifetime” of a variable. –Variables exist from when they are declared until the method in which they are declared has finished execution. For the main method, this is as long as your program is running. For other methods, this is the remainder of ONE execution of the method –If the method is called again, previous variable values would be forgotten Scope: the parts of a program from which a variable can be accessed. –General rule: variables can be ONLY be accessed inside program block { } in which the variables are declared –Parameters: can only be accessed inside their method body.

25 Scope class Scope { public static void method1( int x ) { int y = 1;... } public static void method2( ) { int y = 2; int x = 3;... for (... ) { int x = 4;... }... } x = 4 y = 1 y = 2 x = 3 x

26 Passing of values to/from methods When a call is made… 1.Execution of the calling method is suspended. 1.Memory is allocated for parameters and local variables of primitive types ( int, double, char, boolean ) in the called method. 1.Initial values for parameters of primitive types are COPIED from the corresponding arguments of the call. 1.Parameters of reference types are associated to the arrays or objects that the corresponding arguments refer to. 1.Execution of method body begins. When the method body finishes, the return value is COPIED back to the calling method and the calling method resumes execution. All other values in the called method are forgotten.

27 Arrays as Parameters An array is a reference type. When an array is passed from one method to another method, it is the reference that is passed to the method, not the array. The result is that there are (temporarily) two references to the same array. While we cannot modify the reference, we can modify the contents of the array. These changes to the array contents will remain after the method returns. –The copy of a variable of a primitive type is trashed when the method returns. –For an array, it is the copy of the reference that is trashed on return.

28 Passing primitive and reference types to a method anInt 4 anArray 532 length 3 4 At caller: m(anInt,anArray): At called method: m(int x, int[] y) copy yx

29 Parameter passing The parameter values that are passed will remain unaffected by calling another method. However, if you pass a reference variable, the object to which the reference points CAN be modified internally. –It is the reference that cannot be changed.

30 Program Organization (1) A class can contain a set of methods, in addition to main : public class VelocityMethod { public static void main(String[] args) { // Main method body } public static double findDistance( double x0, double v0, double t ) { // findDistance() method body }

31 Program Organization (2) If one method is calling another method in the same class, then you only need the method name. aDistance = findDistance( 3.0, 4.0, 7.0 ); If one method is calling another method in a different class, you will need to add the class name: aDistance = VelocityMethod.findDistance( 3.0, 4.0, 7.0 ); To set this up, one of four conditions must be met: 1.The class must be one of the classes pre-loaded by Java (e.g. Math, System, …) 2.The class is in the software development kit, and an import statement is used (e.g. DecimalFormat ) 3.The.class file for the called class is in the same folder on your computer (e.g. Keyboard ) 4.The “classpath” is set in Dr. Java, where the classpath contains a list of folders to search for.class files.

32 Example: Statistics Create a class called Statistics with methods for –reading an array of doubles –squaring a value –finding the mean of an array –finding the standard deviation –a main method that calls the above methods to read an array and print the mean and standard deviation of all the values.

33 Overall class structure class Statistics { public static void main (String[] args) { } public static double[] readDoubleArray( ) { } public static double standardDeviation( double[] x ) { } public static double mean( double[] x ) { } public static double xSquared( double x ) { }

34 Method to read array values public static double[] readDoubleArray( ) { double[] theArray; // Array of values entered by user int arraySize; // Size of 'theArray' int index; // Current array position System.out.println( "Enter an array of values."); System.out.println( ); System.out.println( "How many values in the array?" ); arraySize = Keyboard.readInt(); theArray = new double[arraySize]; for ( index = 0; index < arraySize; index++ ) { System.out.println( "Enter value at position " + index + ":" ); theArray[index] = Keyboard.readDouble(); } // Return result return theArray; }

35 Method to square a value // This method finds the square of a value of type double. public static double xSquared( double x ) { return x * x; }

36 Method to find arithmetic mean // This method finds the arithmetic mean of the values in array 'x'. public static double mean( double[] x ) { // Declare variables double result;// The calculated average. double sum; // Running total of array values. int index;// Array position while calculating sums. // Find sum of array elements. sum = 0.0; for ( index = 0; index < x.length; index++ ) { sum = sum + x[index]; } // Divide sum by number of elements in array. result = sum / x.length; return result; }

37 Method to find standard deviation // This method finds the standard deviation of the values in array 'x'. public static double standardDeviation( double[] x ) { double average;// The average of the array values. double sum;// Running total of squares of differences from average double result; int index;// Array position while calculating sums. // Find average using method average = mean( x ); // Now, calculate sum of squares of differences from the mean sum = 0.0; for ( index = 0; index < x.length; index++ ) { sum = sum + xSquared( x[index] - average ); } // Final standard deviation calculation result = Math.sqrt( sum / ( x.length - 1 ) ); return result; }

38 Main method public static void main (String[] args) { // Declare variables double[] x; // Array of values for which to find statistics double average; // Average of all values in x. double stDev; // Standard deviation of all values in x DecimalFormat df; // Used to format output // Set up decimal formatter df = new DecimalFormat("#0.00"); // Read array x = readDoubleArray( ); // Find and print mean average = mean( x ); System.out.println( "The arithmetic mean is " + df.format( average ) ); // Find and print standard deviation stDev = standardDeviation( x ); System.out.println( "The standard deviation is " + df.format( stDev ) ); }

39 Usage as a “library” class The class Statistics represents a useful library of methods that can be used in other classes: class AClass { double mean; double standardDev; double[] x; x = Statistics.readDoubleArray( ); mean = Statistics.mean( x ); standardDev = Statistics.standardDeviation( x ); }