Chapter 6- Arrays. Overview n What are arrays? n Declaring/initializing arrays. n Using arrays. n Arrays details. n Using arrays with classes/ in classes.

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

Arrays and ArrayLists Ananda Gunawardena. Introduction Array is a useful and powerful aggregate data structure presence in modern programming languages.
CompSci Searching & Sorting. CompSci Searching & Sorting The Plan  Searching  Sorting  Java Context.
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
CS102 A Wide Array of Possibilities CS 102 Java’s Central Casting.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
©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.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
1 Arrays In many cases we need a group of nearly identical variables. Example: make one variable for the grade of each student in the class This results.
© The McGraw-Hill Companies, 2006 Chapter 5 Arrays.
1 Lecture 9  Arrays  Declaration  Initialization  Applications  Pointers  Declaration  The & and * operators  NULL pointer  Initialization  Readings:
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
Alice in Action with Java
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
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
Arrays. Objectives Learn about arrays Explore how to declare and manipulate data into arrays Learn about “array index out of bounds” Become familiar with.
Chapter 9 Introduction to Arrays
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Computer Science: A Structured Programming Approach Using C1 Objectives ❏ To understand the basic concepts and uses of arrays ❏ To be able to define C.
Java Unit 9: Arrays Declaring and Processing Arrays.
Chapter 5- Even more about objects and methods. Overview n Designing methods n Methods, methods, methods n Overloading methods n Constructor methods n.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with 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.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Lists in Python.
chap8 Chapter 8 Arrays (Hanly) chap8 2 Data Structure Simple data types use a simple memory to store a variable. Data Structure: a.
Chapter 8 Arrays and Strings
Chapter 6 Arrays Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
EGR 2261 Unit 8 One-dimensional Arrays  Read Malik, pages in Chapter 8.  Homework #8 and Lab #8 due next week.  Quiz next week.
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.
Chapter 8: Arrays.
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
CS107 References and Arrays By Chris Pable Spring 2009.
Lecture 7 Introduction to Programming in C Arne Kutzner Hanyang University / Seoul Korea.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Chapter 8 Sorting and Searching Goals: 1.Java implementation of sorting algorithms 2.Selection and Insertion Sorts 3.Recursive Sorts: Mergesort and Quicksort.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
1 Arrays and Strings Lecture: Design Problem l Consider a program to calculate class average Why?? ?
Arrays An array is a data object that can hold multiple objects, all of the same type. We can think of an array as a storage box which has multiple compartments.
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,
Composition When one class contains an instance variable whose type is another class, this is called composition. Instead of inheritance, which is based.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 7.
Arrays Version 1.1. Topics Tables of Data Arrays – Single Dimensional Parsing a String into Multiple Tokens Arrays - Multi-dimensional.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 2 – August 23, 2001.
IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD
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.
CS 180 Recitation 7 Arrays. Used to store similar values or objects. An array is an indexed collection of data values of the same type. Arrays are the.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
C++ Array 1. C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used.
ARRAYS Multidimensional realities Image courtesy of
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Chapter 9 Introduction to Arrays Fundamentals of Java.
Arrays Chapter 7.
EGR 2261 Unit 10 Two-dimensional Arrays
Computer Programming BCT 1113
Chapter 7 Part 1 Edited by JJ Shepherd
7 Arrays.
A Wide Array of Possibilities
Presentation transcript:

Chapter 6- Arrays

Overview n What are arrays? n Declaring/initializing arrays. n Using arrays. n Arrays details. n Using arrays with classes/ in classes. n Sorting/searching arrays. n Multidimensional arrays. n Review

Arrays, what are they?

What are arrays? n An array is a large collection of variables that are all of the same data type. n It allows us to have a large number of similar variables without having to declare each one individually.

What are arrays used for? n Think back to the grocery purchase program that we did. Imagine instead of having only five items (and declaring five Purchase objects) we had 100 items the user could choose. Since much of the code for each Purchase object is similar, we could just have an array and one piece of code to repeatedly do stuff to that array.

More on arrays n Arrays are like mailboxes. They have a collective name (say the zip code for the University), an index (your box number), and a value (any mail in your box). Name 0123 Value Index Value43105

Arrays n Arrays are actually objects (though they don’t look like it). They are initialized with the new operator. They store a memory address in their variable. n We’ve already seen them, we just haven’t used them.

Declaring and initializing arrays

Declaring arrays. n We declare an array in a very similar way to how we declare variables. The only difference is the [ ] symbols. int [] blar; double [3] muglets; String [] args;

Initializing arrays. n There are lots of ways to initialize arrays. blar=new int[20];//blar now has 20 0’s. muglets = new int[2]; //muglets now has 2 0’s muglets[0]=2.3; muglets[1]=1.2; String [] args = {“Hello”, “How”, “are”, “you”};

Array indices n Arrays are indexed from 0 to (the length of the array –1). Remember this. It will cause you immeasurable grief in programming. The index always starts a 0. blar = new int[20]; //indexed 0-19 muglets = new double[4]; //indexed 0-3 args = {“Howdy”, “there”}; //indexed 0-1 int [] lonely = {1}; //indexed 0-0

Declaring and initializing n Can declare and initialize arrays in just one statement(this is the usual way). double [] muglet = new double[4]; String [] words = {“Hello”, “Howdy”}; int [] lonely = {1};

What is happening int [] blar = {1,7,4,6}; blar

Which of the following are valid declarations/initializations of arrays? int arg = new int(5); int arg = new int[10]; double [] blar; blar = new double[15]; String [] muglet = “Hello”; char [] yadda = “Howdy”; int [] someNum = {1,5,7}; Not valid Valid

What are the indices of the following arrays? int [] arr = new int[10]; double [] yadda = new double[1]; String [] hello = {“Hello, Hello, Hello”}; int [] number = {1,5,10,15,20}; int I = 4; double sum = new double[I];

Using Arrays

Accessing arrays n To get at the information inside of an array, we again use the [ ] operators. n To access the i th element of an array called arrayName, we say arrayName[i]. n Remember, we start at index 0, with the 0 th element.

Using arrays double []someArray = {1.4, 2.6,2.1, 3.4,8.4}; double I = someArray[0];//I=1.4 double j = someArray[1];//j = 2.6 double k = someArray[2];//k = 2.1 double m = someArray[3];//m = 3.4 double n = someArray[4];//n=8.4 double o = someArray[5];//o = ArrayIndexOutOfBounds Exception

More info on arrays. n The length of an array is also stored in the array object, and we can access it through the public length variable. arrayName.length n We can only read this variable. We cannot set it.

Common uses of length. //assume arr is an array. … for(int I=0; I<arr.length;I++) { System.out.println(arr[I]); }

Which are valid uses of arrays? int []muglets = new int[5]; double []blar = new double[3]; … muglets(0) = 3; muglets[3] = 24; muglets[5] = 3; blar.length = muglets.length; if(muglets.length == blar.length) {… } Not valid Valid Not valid Valid

Array Details

Some more rules about arrays. n All of a single array should be of the same type. You can’t have a mixed array, part String and part integer. You can only store one type of data in a single array. n Array names are just memory addresses. Thus they act more like objects than primitives. You can’t just use = and == to copy an array or compare arrays. Have to do it element by element.

More rules. n Don’t go out of bounds! Stay within your array. You WILL make this mistake. Often. It WILL crash your program. n If you don’t give an initialization list to an array, the computer just initializes all of the data in the array to some default value for the data type. If your data type is a class, it just stores null in the array position(you need to construct a new object when before you use this!).

Array details review n What is output to the screen? int []someArray = new int[5]; someArray[5] = 3; System.out.println(someArray[5]); n What does the name of the array store? What two common operations can’t you do with arrays? Nothing

Array Details Review n What is output to the screen? int [] someArray = new int[20]; System.out.println(someArray[5]); n Is the following valid? int [] someArray = new int[20]; someArray[5] = “1”; 0 No

Using arrays with classes / in classes.

Using arrays in classes n We can use an array in any class that we want. They can be private instance variables. They can be public static variables. They can be variables that are local to a method. n We can also pass arrays to methods, return arrays from methods, or pass single elements from arrays to a method.

Using arrays in classes … private int [] blar; //want to initialize //in a constructor or //in some method. public static double [] mug = new double[15]; private Purchase []itemsOffered; …

Passing single elements to a method n If a method requires a variable of the same data type as your array base type, then you can pass a single element to the method. double []blar = {3.0,4.0}; Triangle a = new Triangle(); a.setBase(blar[0]); //a.setBase(3.0); b.setHeight(blar[1]); //a.setHeight(4.0);

Passing arrays to methods n We can also pass whole arrays to methods(notice, every main method accepts a String array). … public void doSomething(int [] someArray) {…} … int [] blar = new int[20]; … doSomething(blar); Don’t use array index things [ ]. Just the name. If you use the [ ] symbols, you will pass a single element, not the whole array. Indicates it requires an array

Returning arrays from methods n We can also return arrays from methods, if we like. Be careful, this is just like returning a non-String object. If you want the array to be private, it is better to make a copy and return it. public int[] doSomething() {int [] someArray = new int[20]; … return someArray; } Again, want to return the whole array, so we use the whole name, no [ ] symbols. Indicates going to return an array.

Review - Arrays in classes and methods. n Can we use arrays in classes? Is there anything special that we have to do to use them in classes? n How do we pass or return a single element of an array? n Make a method declaration that is public, returns nothing, is called “muglet”, and accepts an integer array as a parameter.

Review- Arrays in Classes. n Make a method declaration for a method that is public, returns an array of doubles, is called “blar”, and accepts an array of integers. n Why do we have to be careful when returning an array from a method? What can we do to be safe?

Searching/Sorting

How to find information in arrays n Now that we are able to store information in arrays, we also need to be able to find the information again and retrieve it. n To find information we will perform a searching algorithm on the array(we’ll look for the value in the array).

Sequential search n The sequential search is very simple: We start at the first element in the array, and compare it against what we want to find. We continue this till the last element in the array. If we ever find the value, we’re done. If we get to the end of the array, and we haven’t found it, then the value isn’t in the array.

Sequential search in code int toSearchFor = 5, i; int [] anArray = new int[20]; //anArray gets some values from the user. for(I=0; I<anArray.length; I++) { if(toSearchFor == anArray[I]) { System.out.println(“Found it.”); System.out.println(“At location: “+I); break; } if(I==anArray.length) System.out.println(“Didn’t find it.”);

Other searches n There are other searches we can perform that are sometimes faster. n A binary search can be performed if all of the data is in order(like a phone book) –Look at the halfway point. If you are at too small of a value, disregard the left half and proceed searching the right half. If you are at too large a value, disregard the right half, and look at the left half.

Other searches continued... n Many of these faster searches, such as a binary search, require that our list of information (or array) be sorted. n We must find some way of sorting an array.

Why sorting n Organization in general can make things quicker. We spend less time looking for things, and more time using them. This is why we do sorting. It makes our information easier to find and use. n The first sorting algorithm we will look at is the Selection Sort.

Selection Sort algorithm(smallest to largest). n For each element i in the list. –Find the i th smallest value. –Place this value in the i th position. n This is probably the most intuitive sort algorithm. We need to refine this algorithm more before we can use it in Java code, though.

Selection Sort algorithm refined. n For each i th element in the list –For each of the elements from I on compare against the smallest seen so far. –Swap the i th value in the list with the i th smallest value.

Selection sort code n See the code on page 426 and 427 for the full code of an implementation of the Selection Sort algorithm.

Swapping-Exchanging values in arrays. n Swapping is an important step that occurs in every sorting algorithm. n The idea is to exchange the value from one index with the value located at another index. n For this, we will always need a temporary variable to store the value from one of the elements while it is being overwritten.

Other sorting algorithms. n There are other sorting algorithms out there, and some even run much faster than the selection sort. n If you would like to do some research, look at the Bubble Sort, the Insertion Sort, the Merge Sort, and the Quick Sort.

Sorting examples in action. n View the Sorting demo in the applet demos in the directory you installed Java to (C:\jdk1.3\demo\applets\SortDemo)

Searching/Sorting review. n Explain the Sequential Search algorithm in your own words. n Why do we want to do sorting? n Explain the Selection Sort algorithm in your own words. n Are there faster sorting algorithms than the Selection Sort algorithm?

Sorting Review n Go through the steps to do the Selection Sort on the following list of numbers: 1,5,17,6,3,12,18

Multidimensional Arrays

Multidimensional arrays n We can have arrays with more than a single dimension. n These are used for things like tables of data, game boards, keeping 3/4 dimensional data, weather forecasting, etc. n Can have as many dimensions as you would like, but we usually keep it under 5 dimensions. n Most often we will deal with 2-dimensional arrays.

Declaring multidimensional arrays n Just add an extra set of square brackets [ ] for every dimension. double [][] excelSheet = new double[10][8]; double [][][] temps3D = new double[20][20][20]; char [][] ticTacToeBoard = new char[3][3]; Creates a tic tac toe board with 3 rows, 3 columns Creates a table with 10 rows, 8 columns. Creates a 3-Dimensional cube for storing temperatures in a three dimensional space.

2 dimensional tables. n Our most common multi-dimensional array. n By convention, listed in row-column order. int numRows = 3, numCols = 2; int [][]table = new int[numRows][numCols]; for(int rows = 0; rows <numRows; rows++) for(int cols = 0; cols < numCols; cols++) table[rows][cols] = rows+cols;

What that code created int numRows = 3, numCols = 2; int [][]table = new int[numRows][numCols]; for(int rows = 0; rows <numRows; rows++) for(int cols = 0; cols < numCols; cols++) table[rows][cols] = rows+cols;

Rules about arrays. n Make sure you don’t reverse the row-column ordering. Row-Column. Row-Column. Row- Column. RC, RC, RC, Row-Column, Row- Column, Row-Column. RC. RC. Row- Column. RC. Row-Column. Row-Column. Row Column. Row-Column. Row-Column. n You can pass and return multidimensional arrays to and from methods like any other array. Just make sure you get enough brackets in the method declaration.

Implementation of arrays. n A multi-dimensional array is actually just an array of arrays. int [][][]table = new int[4][10][3]; table[2][5].length; //3 table[2].length; //10 table.length; //4

Multidimensional array review. n Write a declaration and initialization of a 3- dimensional array of integers that is sized 3 by 5 by 7. n Are the following declarations legal? int table = new int [15][23][5][24][13]; double [ ] [ ] anotherTable = new double[2][3];

Multidimensional array review. Table[0][3]= Table[5][4]= Table[1][4]= Table[1][1]= Table[0][0]= Table[6][0]= Table[1][3]= Table[3][4]= Table[4][4]= Table[2][1]= Table[3][0]= Table[3][5]=

Review

Arrays Review n What is an array? n What data types can you use in arrays? n Declare an array of integers called “prices” and initialize it to have size 10. n What are the indices for the prices array?

Arrays Review n What is output to the screen? int [] someArray = new int[20]; System.out.println(someArray[5]); n What is output to the screen? int []someArray = new int[5]; someArray[5] = 3; System.out.println(someArray[5]);

Arrays Review n What is actually stored in an array name? n What are the following values? Prices[3]= Prices[0]= Prices[2]= Prices[6]= Prices.length=

Arrays Review n Run the selection sort on the following numbers: 5,23,1,3,2,15,8

Arrays Review Table[1][1]= Table[0][0]= Table[6][0]= Table[2][1]= Table[3][0]= Table[3][5]=