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.

Slides:



Advertisements
Similar presentations
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
Advertisements

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.
Topic 9 – Introduction To Arrays. CISC105 – Topic 9 Introduction to Data Structures Thus far, we have seen “simple” data types. These refers to a single.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Arrays Clark Savage Turner, J.D., Ph.D. Copyright © 2000 by C Scheftic. All rights reserved. These notes do rely heavily.
Arrays  Writing a program that uses a large amount of information.  Such as a list of 100 elements.  It is not practical to declare.
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.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
1 More on Arrays Passing arrays to or from methods Arrays of objects Command line arguments Variable length parameter lists Two dimensional arrays Reading.
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.
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
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.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 8 “Arrays”
Arrays in Java Selim Aksoy Bilkent University Department of Computer Engineering
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.
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.
© 2011 Pearson Education, publishing as Addison-Wesley 1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 6 focuses.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections.
7. Arrays. Topics Declaring and Using Arrays Some Array Algorithms Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
Comp 248 Introduction to Programming Chapter 6 Arrays Part B Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,
1 Dr. Seuss again: "Too Many Daves"  Did I ever tell you that Mrs. McCave Had twenty-three sons, and she named them all Dave?  Well, she did. And that.
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.
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 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
8-1 Chapter 8: Arrays Arrays are objects that help us organize large amounts of information Today we will focuses on: –array declaration and use –bounds.
CSE 501N Fall ‘09 08: Arrays 22 September 2009 Nicholas Leidenfrost.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 7 Arrays 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
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.
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.
1 Objects for Organizing Data -- Introduction zAs our programs get more sophisticated, we need assistance organizing large amounts of data zChapter 6 focuses.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
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];
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
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.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
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.
For Friday Read No quiz Program 6 due. Program 6 Any questions?
Arrays. Arrays are objects that help us organize large amounts of information.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Chapter 7 Arrays…. 7-2 Arrays An array is an ordered list of values An array of size N is indexed from.
Introduction to programming in java Lecture 21 Arrays – Part 1.
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.
Lecture 5 array declaration and instantiation array reference
Arrays of Objects October 9, 2006 ComS 207: Programming I (in Java)
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Chapter VII: Arrays.
CSC 211 Java I for loops and arrays.
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.
Defining methods and more arrays
int [] scores = new int [10];
Arrays in Java.
Visual Programming COMP-315
Arrays of Objects October 8, 2007 ComS 207: Programming I (in Java)
Arrays.
Presentation transcript:

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 as parameter l Array Cloning l Preview: Modelling Multi-Dimensional Arrays

2 Why do we need data 1-D array? l There are many applications where several data values are needed in the memory at same time. l Example, counting number of students who perform below average in a class of 30. l Obviously we need to scan through the list of values two times; » first to compute the average and »second to count those below average. l To solve this problem, do we need to declare 30 variables or do we read the values the second time? l Both of these solutions are not convenient l This is even more so when data size is expected to grow very larger. l One convenient solution to this and similar problems is array. l An array is a contiguous list of memory cells that can be identified using a single variable.

3 Array Declaration l An array is declared as shown below int [] grades = new int[10]; l Another way to declare array, which is not as readable as above is: int grades[] = new int[10]; l Each of the above methods declares an int array of size 10 which cab be shown as a diagram as below, but we discourage the use of the second method: l Other examples of array declaration are shown below. Notice that the last example where two arrays are declared at the same time is discouraged. float[] prices = new float[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750]; int[] first = new int[100], second = new int [200]; grades Index

4 Bounds Checking Once an array is created, it has a fixed size Each array object has a public constant called length that stores the size of the array The length of an array object is referenced through the array name  just like any other object: grades.length An index used in an array reference must specify a valid element -- must be in the range 0 to N-1 for an array of N elements. The Java interpreter will throw an exception if an array index is out of bounds. This is called automatic bounds checking.

5 Initializer List An initializer list can be used to instantiate and initialize an array in one step The values are delimited by braces and separated by commas as shown below int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476}; char[] letterGrades = {'A', 'B', ‘C’ 'D', 'F'}; Notice that in the above examples, it is actually the compiler that fills the gap. Thus, in the first example, the compiler would do the following: int[] units = new int[10]; units[0]=147; units[1]=323;...; units[9]=476; Observe that when an initializer list is used: the new operator is not used no size value is specified

6 Accessing elements of an Array A particular cell in an array can be referenced using the array name followed by the index of the cell in brackets. For example, the following statement stores 20 in the cell whose index is 4 (cell number 5) grades[4] = 20; The following example demonstrates array index processing. Each cell is initialized to zero. class FillOneDArray { public static void main (String args[]) { int[] grades = new int[10]; for (int i=0; i < grades.length; i++) grades[i] = 0; } Notice that the only modification needed for the above function to handle a different array size, say 20, is in line 3. The loop remains the same. grades 20 Index

7 Passing Array as a parameter l An entire array can be passed to a method as a parameter l Like any other object, the reference to the array is passed, making the formal and actual parameters aliases of each other l Changing an array element in the method changes the original l Example class ParameterPassingExample { public static void main(String [] args){ int i; int [] a = {1, 2, 3, 4}; double d = 5.5; System.out.println("After initialization"); for (i = 0; i < 4; i++) System.out.println("a["+i+"]="+a[i]); System.out.println("d = " + d); System.out.println("Calling tryToChange."); tryToChange(a, d); System.out.println("Back from tryToChange"); for (i = 0; i < 4; i++) System.out.println("a["+i+"]="+a[i]); System.out.println("d = " + d); }

8 Passing Array as a parameter (cont’d) private static void tryToChange(int [] arr, double dd) { int i; dd = 3.14; arr[0] = 55; arr[3] = 100; for (i = 0; i < 4; i++) System.out.println("arr["+i+"]="+arr[i]); System.out.println("dd = " + dd); } Sample output After initialization a[0]= 1 a[1]= 2 a[2]= 3 a[3]= 4 d = 5.5 Calling tryToChange... arr[0]= 55 arr[1]= 2 arr[2]= 3 arr[3]= 100 dd = 3.14 Back from tryToChange a[0]= 55 a[1]= 2 a[2]= 3 a[3]= 100 d = 5.5

9 More examples: Printing students who score below average in a quiz l Suppose we have ID number and scores of students in a quiz stored in a text file, QuizScores.txt. l The first column represents the ID numbers, the second represent the scores and the values -1, -1 indicates end of file. l Then the following program prints the scores and statistics such as min, max, mean and list of students who performed below average. import TextIO; class StatisticsExample { private static final int MAX_STUDENTS = 50; private static final double INFINITY= ; private static final String DATA_FILE= "QuizScores.txt"; public static void main (String[] args) throws java.io.IOException { long[] ids = new long[MAX_STUDENTS]; double[] scores = new double[MAX_STUDENTS]; double min=INFINITY, max= -INFINITY, sum=0.0; double mean; long minID = -1, maxID = -1; int numOfStudents = 0;

10 More examples: Printing students below average in a quiz (cont’d) // declare a channel to data source TextIO in = new TextIO(DATA_FILE); //other variables int i; do { ids[numOfStudents] = in.readLong(); scores[numOfStudents] = in.readDouble(); numOfStudents++; } while (ids[numOfStudents-1] > 0); numOfStudents--; for (i = 0; i < numOfStudents; i++) { sum += scores[i]; if (scores[i] > max) { max = scores[i]; maxID = ids[i]; } if (scores[i] < min) { min = scores[i]; minID = ids[i]; }

11 mean = (1.0/numOfStudents) * sum; System.out.println("Quiz Scores and statistics."); for (i = 0; i < numOfStudents; i++) System.out.println(ids[i] +"\t"+ scores[i]); System.out.println("\nNumber of Students in the Class: " + numOfStudents); System.out.println("\nClass Average: " + mean); System.out.println("\nMinimum Score of: " + min + " is scored by the person with ID " + minID); System.out.println("\nMaximum Score of: " + max + " is scored by the person with ID " + maxID); System.out.println("\n\nList of students below average"); for (i=0; i<numOfStudents; i++) if (scores[i]<mean) System.out.println(ids[i]+"\t"+scores[i]); } )

12 More examples: Printing students below average in a quiz (cont’d) Sample Output Quiz Scores and Statistics Number of Students in the Class: 8 Class Average: Minimum Score of: 2.5 is scored by the person with ID Maximum Score of: 9.5 is scored by the person with ID List of All students below average

13 Array cloning l The following example shows how we may make a copy of an array. class ArrayCloningExample { private static final int ELEMENTS = 5; public static void main (String[] args) { int[] a = new int[ELEMENTS]; int[] b; int i; //fill the i-th element of a with i^2 and print System.out.println("Contents of a[]"); for(i = 0; i < a.length; i++) { a[i] = i * i; System.out.println("i = "+i+" a["+i+"]=\t“ + a[i]); } // duplicate the array a into b b = (int []) a.clone(); // print out the array b System.out.println("Contents of b[] immediately after duplication from a[]"); for(i = 0; i < b.length; i++) System.out.println("i = "+i+" b[" +i+ "] =\t“ + b[i]); // Modify the array b by doubling every element for(i = 0; i < b.length; i++) b[i] *= 2;

14 Array cloning (cont’d) System.out.println("Contents of a[] and b[] after doubling elements of b[]"); for(i = 0; i < ELEMENTS; i++) System.out.println("i = " + i + " a[" + i + "] =\t"+a[i]+"\t\tb[" + i + "] =\t" + b[i]); } Sample Output: Contents of a[] i = 0 a[0] = 0 i = 1 a[1] = 1 i = 2 a[2] = 4 i = 3 a[3] = 9 i = 4 a[4] = 16 Contents of b[] immediately after duplication from a[] i = 0 b[0] = 0 i = 1 b[1] = 1 i = 2 b[2] = 4 i = 3 b[3] = 9 i = 4 b[4] = 16 Contents of a[] and b[] after doubling elements of b[] i = 0 a[0] = 0 b[0] = 0 i = 1 a[1] = 1 b[1] = 2 i = 2 a[2] = 4 b[2] = 8 i = 3 a[3] = 9 b[3] = 18 i = 4 a[4] = 16 b[4] = 32