Arrays Horstmann, Chapter 8. arrays Fintan 012345 Array of chars For example, a String variable contains an array of characters: An array is a data structure.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
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.
IMPLEMENTING CLASSES Chapter 3. Black Box  Something that magically does its thing!  You know what it does but not how.  You really don’t care how.
CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
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.
Liang, Chpt 5 continued. Sorting arrays The telephone book is easy to use, because the entries are sorted Sorting is a common task, and many many algorithms.
 2003 Prentice Hall, Inc. All rights reserved. 7.1 Introduction Arrays –Data structures which reference one or more value –All items must have same data.
Arrays Liang, Chpt 5. arrays Fintan Array of chars For example, a String variable contains an array of characters: An array is a data structure.
Arrays  Writing a program that uses a large amount of information.  Such as a list of 100 elements.  It is not practical to declare.
Chapter 10 Arrays. Topics Declaring and instantiating arrays Array element access Arrays of objects Arrays as method parameters Arrays as return values.
Loops Notes adapted from Dr. Flores. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while”
Arrays. Arrays  When a value is to be used in a program, a variable is declared to hold that value  What about storing the results of exams for a large.
Lecture 7: Arrays Yoni Fridman 7/9/01 7/9/01. OutlineOutline ä Back to last lecture – using the debugger ä What are arrays? ä Creating arrays ä Using.
Introduction to Computers and Programming Lecture 15: Arrays Professor: Evan Korth New York University.
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.
Primitive Data Types byte, short, int, long float, double char boolean Are all primitive data types. Primitive data types always start with a small letter.
CS 106 Introduction to Computer Science I 10 / 04 / 2006 Instructor: Michael Eckmann.
Array Must declare a variable to reference the array double [] mylist; // cannot double list[20]; Or double mylist[]; The declaration doesn’t allocate.
CS 106 Introduction to Computer Science I 02 / 20 / 2008 Instructor: Michael Eckmann.
COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007.
 2003 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Arrays Introduction to Computers and Programming in.
Arrays. Arrays  When a value is to be used in a program, a variable is declared to hold that value  What about storing the results of exams for a large.
CS 106 Introduction to Computer Science I 02 / 19 / 2007 Instructor: Michael Eckmann.
© The McGraw-Hill Companies, 2006 Chapter 7 Implementing classes.
Arrays. A problem with simple variables One variable holds one value –The value may change over time, but at any given time, a variable holds a single.
Java Unit 9: Arrays Declaring and Processing Arrays.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.
Arrays (Part 1) Computer Science Erwin High School Fall 2014.
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.
The basics of the array data structure. Storing information Computer programs (and humans) cannot operate without information. Example: The array data.
JAVA Array 8-1 Outline  Extra material  Array of Objects  enhanced-for Loop  Class Array  Passing Arrays as Arguments to Methods  Returning Arrays.
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 and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
Chapter 8: Arrays.
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.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
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.
Problem Solving for Programming Session 8 Static Data Structures.
1 Building Java Programs Chapter 7: Arrays These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted, sold, or.
Lecture 101 CS110 Lecture 10 Thursday, February Announcements –hw4 due tonight –Exam next Tuesday (sample posted) Agenda –questions –what’s on.
1 On (computational) simplicity We are trying to teach not just Java, but how to think about problem solving. Computer science has its field called computational.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Odds and Ends. CS 21a 09/18/05 L14: Odds & Ends Slide 2 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights.
CS 139-Programming Fundamentals Lecture 11B - Arrays Adapted from a presentation by Dr. Rahman Fall 2014.
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.
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.
Arrays-. An array is a way to hold more than one value at a time. It's like a list of items.
BIT115: Introduction to Programming
Introducing Arrays. Too Many Variables?  Remember, a variable is a data structure that can hold a single value at any given time.  What if I want to.
int [] scores = new int [10];
Week 6 - Friday.  What did we talk about last time?  Loop examples.
Midterm Review Tami Meredith. Primitive Data Types byte, short, int, long Values without a decimal point,..., -1, 0, 1, 2,... float, double Values with.
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?
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.
Lecture 7: Arrays Michael Hsu CSULA 3 Opening Problem Read one hundred numbers, compute their average, and find out how many numbers are above the average.
Data Structures and Algorithms revision
Chapter 6 Arrays Solution Opening Problem
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.
BIT115: Introduction to Programming
int [] scores = new int [10];
Single-Dimensional Arrays chapter6
Arrays in Java.
Variables and Computer Memory
Week 7 - Monday CS 121.
Presentation transcript:

Arrays Horstmann, Chapter 8

arrays Fintan Array of chars For example, a String variable contains an array of characters: An array is a data structure which stores several elements All elements are the same type (e.g. int, double, char, String....) String myName = “Fintan”; public static int length(){…} public static boolean equal(String x){…} creates a box like this in the computer’s memory: Each box’s number is called its index These are some of the methods that Strings have (that the String class has) … public static char charAt(int i){…} Array of char s: each char in a numbered box. myName

Why bother with arrays? Many programs need to work with many numbers at once E.g. a program to produce a telephone directory Keeping track of many separate variables is tiresome and error prone So we keep them all together, like peas in a pod or beads on a string.....or socks in the sock drawer or

Example: keeping track of class scores next score: 87 next score: 62 next score: 45 next score: 64 next score: 30 next score: 88 We will store these numbers in an array of int s called scores When we create an array in a java program, Java sets aside an area of memory large enough to hold that array. The variable name for the array points at (holds the memory location of) that area of memory (e.g. scores above points at the array location) The memory space needed to hold an array depends on (1) how many elements there will be in the array, (2) how big the element type is scores

Declaring and creating an array int[] scores; // declaration scores = new int[6]; // creation int[] means “an array of integers”. This first line just tells java that scores will point to (that is, hold the memory location of) an array of integers ( int s). int[] scores; means scores is the name for this array of integers. new int[6] means “set aside new memory space for an array of six int s”. new is a java command meaning “create a new space in memory for” scores = new int[6]; tells java to set the variable scores so that it points to (has the memory address of) that newly created array.

Declaring and creating in one go scores // both together int[] scores = new int[6]; This sets aside memory space for an array of six int s, and sets the variable scores to point to that memory space. Now, we’ve (1) created an array variable, (2) created memory space for an array and (3) set the variable to point to that space. But we haven’t put anything into the array yet. Before anything is put into the boxes in an array, they are given a default value (zero for numbers). So our array looks like this:

Indexing into an array To refer to elements in an array, we use the array name and the index of the element we want. The first element is scores[0]. Since we created space for 6 elements in the scores array, the last element is scores[5]. // assigning some values to array elements String x; // to hold the users input for(int i=0; i<scores.length; i++) { x=JOptionPane.showInputMessage(null,”enter score “+i); scores[i] = Integer.parseInt(x); } scores[0] = 87; scores[1] = 62; // and so on Counting from 0 often gives people problems with arrays. Remember, for an array with X elements, the last element has the index X-1 Also, a variable called length gives us the total length of the array.

Quick declaration, creation and initialization double[] myList = {1.9, 2.9, 3.4, 3.5}; The length of this array is 4 int len = myList.length; // len is now 4 Note, we use myList.length, not myList.length() myList.length() would be a method belonging to the array myList. But there is no such method. myList.length is a variable belonging to the array that tells you the number of elements for which that array was created. Note also, we did not use the keyword new in this form!

Initialization When we create an array, each element is given a default value For numbers, this is 0 (or 0.0) For characters it is the null character For objects, it is the null reference (more on objects later) For booleans, it is false

Doing things to elements in an array All elements are of the same kind (int, double, BankAccount, objects, Ball objects etc) The length of the array is known To do anything to each element, we invariably use a for-loop // print out each element for(int i=0; i<myList.length; i++) { System.out.print(myList[i] + " "); }

Common errors with Arrays There is no space before square brackets: There is always a space (or a semicolon) after square brackets int[] scores; scores = new int[6]; int[] (type given, no number) means ‘declare an array variable that will hold things of this type’ int[6] (type given, number given) means ‘create new space in memory for an array of this number of elements of this type’ scores[3] (variable name given not type; number given) means ‘return the element in box indexed by number from array pointed to by variable name’

Off-by-one errors The first index in an array is always 0 The index of the last element is array.length - 1 What happens if we try to access an element which is not in the range [0..length-1]? This common error generates an ArrayIndexOutOfBoundsException This is not caught by the compiler! An exception is a run-time error Trying to access myList[4] when myList is of length 4 is called an off-by-one error very common!!!

Objects in arrays Arrays don’t just contain integers. We can create arrays containing BankAccount objects, Ball objects, Strings, etc. When we want to store multiple pieces of information about the items in our array, using Objects is particularly suitable. For example, a Bank might want to have an array (a list) of all the accounts it holds. Each account should hold a customers name and the balance of their account. We first define a bankAccount class, and then each time we want to add a customer’s account to our list (our array) we create a new object from that class and add it to the next empty cell in our array.

class BankAccount{ private double balance; private String name; public void deposit(double value) { balance = balance + value; } public void withdraw(double withdrawAmount) { balance = balance - withdrawAmount; } public double getBalance(){ return balance; } public double getName(){ return name; } public BankAccount(String customerName) { name = customerName; balance = 0; } public BankAccount(String customerName, double deposit) { name = customerName; balance = deposit; } } Here’s a simplified version of the BankAccount class. Every object from this class will hold a customer’s name and the balance in their account.

class BankAccountTester{ private BankAccount[] accountArray= new BankAccount[10]; public static void main(String[] args) { for(int x = 0; x < accountArray.length; x++){ String n; n= JOptionPane.showInputDialog(null,” customer name? ”); String dString; dString= JOptionPane.showInputDialog(null,” deposit ?”); double d = Double.ParseDouble(dString); accountArray[x] = new BankAccount(n,d); } for(int x = 0; x < accountArray.length; x++){ System.out.println(accountArray[x].getName()+ “ ” + accountArray[x].getBalance() ); } System.exit(0); } Second loop goes through the array, printing out the information on each bankaccount object. First loop populates the array, putting a new BankAccount object in each box in the array.

Searching for an element: Linear Search Q: does the number 5 occur in the following array? Q: what about this one?

Linear Search in a method // method to find a key in a list public static int linearSearch(int key, int[] list) { for(int i=0; i<list.length; i++) { if(key == list[i]){ return i; } } return -1; // return –1 if the key is not found // otherwise return key’s location }