1 One-Dimensional Arrays  What are and Why 1-D arrays?  1-D Array Declaration  Accessing elements of a 1-D Array  Initializer List  Passing Array.

Slides:



Advertisements
Similar presentations
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-2: Arrays as Parameters reading: , 3.3 self-checks: Ch. 7 #5, 8,
Advertisements

1 Various Methods of Populating Arrays Randomly generated integers.
Arrays. What is an array An array is used to store a collection of data It is a collection of variables of the same type.
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Lecture 05 - Arrays. Introduction useful and powerful aggregate data structure Arrays allow us to store arbitrary sized sequences of primitive values.
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-1: Arrays reading: 7.1 self-checks: #1-9 videos: Ch. 7 #4.
1 2-D Arrays Overview l Why do we need Multi-dimensional array l 2-D array declaration l Accessing elements of a 2-D array l Declaration using Initializer.
Introduction to Computers and Programming Lecture 15: Arrays Professor: Evan Korth New York University.
1 More on 1-D Arrays Overview l Array as a return type to methods l Array of Objects.
1 One-Dimensional (1-D) Array Overview l Why do we need 1-D array l 1-D array declaration and Initialization l Accessing elements of a 1-D array l Passing.
©2004 Brooks/Cole Chapter 8 Arrays. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Sometimes we have lists of data values that all need to be.
1 Modelling 1-D Array Overview l Why do we need 1-D array l 1-D array declaration and Initialization l Accessing elements of a 1-D array l Passing Array.
1 Dynamic Arrays  Why Dynamic Arrays?  A Dynamic Array Implementation  The Vector Class  Program Example  Array Versus Vector.
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.
Looping Yong Choi School of Business CSU, Bakersfield.
Slides prepared by Rose Williams, Binghamton University Chapter 6 Arrays.
1 More on 1-D Array Overview l Array as a return type to methods l Array of Objects l Array Cloning l Preview: 2-D Arrays.
CMSC 104, Version 8/061L22Arrays1.ppt Arrays, Part 1 of 2 Topics Definition of a Data Structure Definition of an Array Array Declaration, Initialization,
Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
French Territory of St. Pierre CSE 114 – Computer Science I 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.
ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
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.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Review of ICS 102. Lecture Objectives To review the major topics covered in ICS 102 course Refresh the memory and get ready for the new adventure of ICS.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Department of Computer Engineering Computer Programming for International Engineers I NTERNATIONAL S CHOOL OF E NGINEERING C HULALONGKORN U NIVERSITY.
1 Array basics. Data Structures Sometimes, we have data that have some natural structure to them  A few examples: Texts are sequences of characters Images.
Method Overloading  Methods of the same name can be declared in the same class for different sets of parameters  As the number, types and order of the.
EE 422C Day 2 Java, Eclipse. Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
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.
Building Java Programs Chapter 7 Arrays Copyright (c) Pearson All rights reserved.
Arrays. Collections We would like to be able to keep lots of information at once Example: Keep all the students in the class Grade each one without writing.
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.
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 and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
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.
BIT115: Introduction to Programming
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];
Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.
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.
Exam 2 EXAM 2 Thursday!!! 25% of Final Grade Know: loops, switch/case Files Input failure (e.g. scan.hasNextInt())
1 Arrays Chapter 8. Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize.
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.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Building Java Programs Chapter 7 Arrays Copyright (c) Pearson All rights reserved.
ARRAYS.
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Chapter VII: Arrays.
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Arrays 2/4 By Pius Nyaanga.
Arrays Part 1 Topic 19 - Stan Kelly-Bootle
Yong Choi School of Business CSU, Bakersfield
Building Java Programs Chapter 7
Building Java Programs
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.
Building Java Programs
int [] scores = new int [10];
Dr. Sampath Jayarathna Cal Poly Pomona
Arrays in Java.
Suggested self-checks: Section 7.11 #1-11
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Presentation transcript:

1 One-Dimensional Arrays  What are and Why 1-D arrays?  1-D Array Declaration  Accessing elements of a 1-D Array  Initializer List  Passing Array as a parameter  What if size is unknown?  Array as return type to methods  Array of Objects

2 What are and Why 1D-arrays?  Some applications require several values in the memory at the same time.  For example: counting the number of students whose grades are above the average in a class of 30  This involves scanning through the grades two times:  First to compute the average and second, to count those above average  How can we scan through 30 grades two times? 1.Declare 30 variables to store the grades – inconvenient double grade1 = Double.parseDouble(stdin.readLine()); double grade2 = Double.parseDouble(stdin.readLine());... double grade30 = Double.parseDouble(stdin.readLine()); double average = (grade1 + grade grade30) / 30; int count = 0; if(grade1 > average) count++; if(grade2 > average) count++;... if(grade30 > average) count++;

3 What are and Why 1D-arrays? (cont’d) 2. Use a loop to find the average and ask the user to re-type the values or re-read them from a file for the second scan --inconvenient double grade, average, sum = 0; for(int i = 1; i <= 30; i++){ grade = Double.parseDouble(stdin.readLine()); sum += grade; } average = sum / 30; int count = 0; for(int i = 1; i <= 30; i++){ grade = Double.parseDouble(stdin.readLine()); if(grade > average) count++; }  Is there a better approach? - Yes, this is what 1-D arrays are for.  An array is a contiguous collection of variables of the same type, referenced using a single variable. The type is called the "base type" of the array.

4 1-D Array Declaration  For any type T, T[ ] is a class, whose instances are arrays of type T.  Thus, the following statement declares a reference variable, b, of type T array: T[] b;  For any positive integer n, the following expression creates a new T[ ] object of size n and stores its reference in b: b = new T[n] ;  As usual, the two expressions can be combined together as: T[] b = new T[n] ;  For example, the following declares an int[], grades, of size 10: int[] grades = new int[10];

5 1-D Array Declaration (cont’d) int[] grades = new int[10];  The declaration of an array of size n creates n variables of base type.  These variables are indexed starting from 0 to n-1.  Each array object has a public instance variable, length, that stores the size of the array.  Thus, the following statement prints 10, the size of grades: System.out.println(grades.length);  Other examples of 1D-array declaration are: double[] price = new double[500]; boolean[] flag = new boolean[20];

6 Accessing elements of a 1-D Array  A particular variable is accessed by indexing the array reference with the index of the variable in bracket: grades[4] = 20;  The following example, initializes each variable with twice its index: int[] grades = new int[10]; for(int i = 0; i < grades.length; i++) grades[i] = 2*i;  The use of grades.length makes the code more general.

7 Accessing elements of a 1-D Array (Cont'd )  The following prints the values of the array initialized by the example in the previous slide. for(int i = 0; i < grades.length; i++) System.out.print(grades[i] + “ “);  Output:  Note: Trying to access an element with an invalid index causes a run-time error: ArrayIndexOutOfBoundsException: int x = grades[10]; // run-time error

8 Initializer List  Initializer list can be used to instantiate and initialize an array in one step: int[] prime = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29}; char[] letterGrade = | ’ A ’, ‘ B ’, ‘C’, ‘ D ’, ‘ F ’ |;  It is actually the compiler that fills the gap. Thus, in the first example, the compiler would add the following: int[] prime = new int[10]; prime[0] = 2; prime[1] = 3;... prime[9] = 29;  Observe that when an initializer list is used:  The new operator is not required.  The size is not required; it is computed by the compiler.

9 Passing Array as a parameter  To make a method accepts an array as argument we must specify its type in the parameter list.  The following method prints the content of an int array passed to it as parameter: public static void printArray(int[] a){ for(int i = 0; i < a.length; i++) System.out.print(a[i]+ “ "); System.out.println(); }  A method can change the values of an array passed to it as parameter: public static void doubleArray(int[] a){ for(int i = 0; i < a.length; i++) a[i] = a[i] * 2; }

10 Passing Array as a parameter (cont'd)  It is only the reference to the actual array that is passed.  Thus, any changes done by a method affect the actual array.  The following uses the two methods of the last slide: public static void main(String[] args){ int[] grades = {5, 7, 6, 8, 10}; System.out.println("Grades before doubling:"); printArray(grades); doubleArray(grades); System.out.println("Grades after doubling:"); printArray(grades); }  The output is: Grades before doubling: Grades after doubling:

11 What if size is unknown?  The size of an array must be specified before it can be created..  If the actual size is not known, a reasonably large size is specified.  An extra variable is then used to keep count of the values stored.. public static void main(String[] args)throws IOException{ BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)); double[]grade = new double[100]; int gradeCount = 0; System.out.print("EnterNextGrade:"); double value = Double.parseDouble(stdin.readLine()); while(value >= 0 && gradeCount < 100){ grade[gradeCount] = value; gradeCount++; System.out.print("EnterNextGrade (negative number to terminate):"); value = Double.parseDouble(stdin.readLine()); } double average = getAverage(grade,gradeCount); System.out.println("The average grade is: “ + average); System.out.println("Grades above average are:"); printAboveAverage(grade, gradeCount, average); }

12 What if size is unknown? (cont’d) public static double getAverage(double[] a, int count){ if(count == 0) throw new IllegalArgumentException(“zero count”); double sum = 0; for(int i = 0 ; i < count; i++) sum = sum + a[i]; return sum/count; } public static void printAboveAverage(double [ ] a, int count, double average){ for(int i =0 ; i < count; i++) if(a[i] > average) System. out. println(a[i]); }

13 Array as return type to methods  Methods can also have arrays as their return type.  The following creates two arrays a and b of same size n and print their dot product: a 0 b 0 + a 1 b 1 + a 2 b a n-1 b n-1 public static double[] createArray(int size) throws IOException{ double[] array = new double[size]; for(int i = 0; i <size; i++){ System.out.print("Enter element #“ + (i+1) + ": "); array [i] = Double.parseDouble(stdin.readLine()); } return array; } public static void main( String [ ] args) throws IOException { int size; System.out.print("Enter array size: "); size = Integer.parselnt(stdin.readLine()); double[] a = createArray(size); double[] b = createArray(size); System.out.println ( "The dot product = "+dotProduct(a, b)); }  The implementation of dotProduct is left as an exercise.

14 Array of Objects  So far, our examples have been on arrays of primitive types.  We can equally create arrays whose elements are objects.  We can create an array to store 10 Student objects as follows: Student[] student = new Student[10];  However, only the references to the Student objects are stored.  The figure shows the array after adding two Student objects. student[0] = new Student(993546, "Suhaim Adil", 3.5); student[1] = new Student(996789, "Jan Usam", 3.9); reference student null Suhaim Adil Jan Usam

15 Array of Objects (cont’d)  The following method takes size, and returns an array initialized with size Student objects. public static Student[] createArray(int size) throws IOException{ Student[] array = new Student[size]; String name; int id; double gpa; for(int i = 0; i < size; i++){ System.out.print("ID Number : "); id = Integer.parselnt(stdin.readLine()); System.out.print("Name : "); name = stdin.readLine(); System.out.print("GPA : "); gpa = Double.parseDouble(stdin.readLine()); array[i] = new Student(id, name, gpa); } return array; }

16 Array of Objects (cont’d)  Each array element is treated exactly as a reference to an object.  For example, to call the getName() method of the object at cell 0: student[0].getName();  The following takes an array of Students and prints those with GPA>=2.0 public static void printGoodStanding(Student[] student){ for (int i=Q; i<student.length; i++) if(student[i].getGPA() >= 2.0) System.out.println(student[i]); }  The two methods are called as follows: public static void main(String[] args) throws lOException { int size; System.out.print("Enter number of students: "); size = Integer.parselnt(stdin.readLine()); Student[] student = createArray(size); printGoodStanding(student); }