Week 6: Arrays 1.  Loops are great  But, without a way to talk about a group of values, we can’t get the full potential out of a loop  Enter: the array.

Slides:



Advertisements
Similar presentations
Chapter 7 Multidimensional Arrays. Defining a two dimensional array elementType[][] arrayName; // Java pro elementType arrayName[][]; // C++ alternate.
Advertisements

Arrays CS177 (Week 06). Announcements ● Project 2 due today ● Project 3 will be posted tomorrow.
Arrays. Topics Tables of Data Arrays – Single Dimensional Parsing a String into Multiple Tokens Arrays - Multi-dimensional.
Week 2: Primitive Data Types 1.  Programming in Java  Everything goes inside a class  The main() method is the starting point for executing instructions.
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 Horstmann, Chapter 8. arrays Fintan Array of chars For example, a String variable contains an array of characters: An array is a data structure.
Introduction to Computers and Programming Lecture 15: Arrays Professor: Evan Korth New York University.
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.
CS 106 Introduction to Computer Science I 03 / 03 / 2008 Instructor: Michael Eckmann.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
Chapter 8 Arrays and Strings
 2007 Pearson Education, Inc. All rights reserved C Arrays.
CS 106 Introduction to Computer Science I 02 / 19 / 2007 Instructor: Michael Eckmann.
CS1061 C Programmuing Lecture 12 Arrays A. O’Riordan, 2004.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Java Unit 9: Arrays Declaring and Processing Arrays.
Week 10 - Monday.  What did we talk about last time?  Method overloading  Lab 9.
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 7 - Wednesday.  What did we talk about last time?  Introduction to arrays  Lab 6.
Lists in Python.
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
Chapter 8 Arrays and Strings
1 DATA STRUCTURES: LISTS. 2 LISTS ARE USED TO WORK WITH A GROUP OF VALUES IN AN ORGANIZED MANNER. A SERIES OF MEMORY LOCATIONS CAN BE DIRECTLY REFERENCED.
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.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 9 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.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
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.
ARRAYS Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall
CS107 References and Arrays By Chris Pable Spring 2009.
Computer Programming 12 Mr. Jean April 24, The plan: Video clip of the day Upcoming Quiz Sample arrays Using arrays More about arrays.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
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.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!
Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Arrays. The array data structure Array is a collection of elements, that have the same data type Integers (int) Floating point numbers (float, double)
Introducing Arrays We will often need to store collections of information –a list of names to sort –a list of values to compute averages, standard deviation,
Week 9 - Monday.  What did we talk about last time?  Method practice  Lab 8.
Arrays-. An array is a way to hold more than one value at a time. It's like a list of items.
Week 9 - Wednesday.  What did we talk about last time?  2D arrays  Queen attacking pawn example  Started Game of Life.
Week 7 - Wednesday.  What did we talk about last time?  Introduction to arrays  Lab 6.
Arrays.
Week 10 - Wednesday.  What did we talk about last time?  Method example  Roulette simulation  Types in Java.
int [] scores = new int [10];
Multidimensional Arrays Computer and Programming.
Arrays in java Unit-1 Introduction to Java. Array There are situations where we might wish to store a group of similar type of values in a variable. Array.
Week 6 - Friday.  What did we talk about last time?  Loop examples.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
Week 5 - Monday.  What did we talk about last time?  Processes  Lab 4.
Copyright © 2013 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Third Edition by Tony Gaddis.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Coding – Week 2 Functions, Arrays, and Objects. Functions  Functions are not a new concept – you’ve been using them already.  void setup() {} and void.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Chapter VII: Arrays.
CSC 211 Java I for loops and arrays.
Arrays in 60 seconds err.. minutes
Computer Programming BCT 1113
Week 7 - Wednesday CS 121.
Week 9 - Monday CS 121.
int [] scores = new int [10];
Building Java Programs
Week 7 - Monday CS 121.
Presentation transcript:

Week 6: Arrays 1

 Loops are great  But, without a way to talk about a group of values, we can’t get the full potential out of a loop  Enter: the array 2

 An array is a homogeneous, static data structure  homogeneous means that everything in the array is the same type: int, double, String, etc.  static (in this case) means that the size of the array is fixed when you create it 3

 The args variable passed into the main() method is an array of type String  This array has a set number of String s (maybe zero) that you can use as input to your program  Now, we are giving you the ability to create and manipulate your own arrays 4

 To declare an array of a specified type with a given name :  Example with a list of type int :  Just like any variable declaration, but with [] type[] name; int[] list; 5

 When you declare an array, you are only creating a variable that can reference an array  At first, it references nothing, also known as null  To use it, you have to create an array, supplying a specific size:  This code creates an array of 100 int s int[] list; list = new int[100]; 6

 As you have seen with args, you can access an element of an array by an index into it, using square brackets and a number  Once you have indexed into an array, that variable behaves exactly like any other variable of that type  You can get values from it and store values into it  Indexing starts at 0 and stops at 1 less than the length list[9] = 142; System.out.println(list[9]); 7

 When you instantiate an array, you specify the length  Sometimes (like in the case of args ) you are given an array of unknown length  You can use its length member to find out int[] list = new int[42]; int size = list.length; System.out.println(“List has “ + size + “ elements”); //prints 42 8

 When you create an int, double, char, or boolean array, the array is automatically filled with certain values  For other types, including String s, each index in the array must be filled explicitly TypeValue int0 double0.0 char‘\0’ booleanfalse 9

 Explicit initialization can be done with a list:  Or, a loop could be used to set all the values: String[] days = {“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”, “Sunday”}; int[] numbers = new int[100]; for(int i = 0; i < numbers.length; i++) numbers[i] = i + 1; 10

 An array takes up the size of each element times the length of the array  Each array starts at some point in computer memory  The index used for the array is actually an offset from that starting point  That’s why the first element is at index 0 11

 Suppose that we have an array of type int of length 10  Java decides what address in memory is going to be used, but let’s say it starts at Addresses Indexes 12

 Arrays are a fixed size list of a single kind of data  A for loop is ideal for iterating over every item and performing some operation  for loops and arrays will crop up again and again  Of course, a while loop can be used with an array, but it is not used as often 13

 Imagine that we have an array of int s called list  Let’s use a for loop to sum up those int s  Super easy!  We don’t even need to know how big the array is ahead of time int sum = 0; for( int i = 0; i < list.length; i++ ) sum += list[i]; 14

 Last week, we showed you how to add a set of numbers together as they were input by a user  Although this is a useful technique, not every operation is possible  We can find the sum or the average of the numbers because we only need to see the numbers once  What operation needs to see the numbers more than once? 15

 Variance is a measurement of how spread out numbers are from their mean  To calculate it, you have to calculate the mean first  The formula is:  Where N is the number of elements, x i is the i th element, and is the mean 16

 Given an array of doubles called number, here’s the code for finding their variance double average = 0; double variance = 0; double temp; for( int i = 0; i < number.length; i++ ) average += number[i]; average /= number.length; for( int i = 0; i < number.length; i++ ) { temp = number[i] – average; variance += temp*temp; } variance /= number.length; 17

 We can represent a deck of cards as an array of 52 items  One easy way is to make each item a String giving the name of the card 18

 Swapping the values of two variables is a fundamental operation in programming  It is going to become more important in arrays because the order of values could be important  The simplest way to swap two variables involves using a third variable as a temporary location 19

 Here is an example of swapping two String s indexed i and j in an array of String s called moniker int i = StdIn.readInt(); int j = StdIn.readInt(); String temp; temp = moniker[i]; moniker[i] = moniker[j]; moniker[j] = temp; 20

 Using the swap code, we can do a random shuffling of a deck  To do so, we go through each element of the array, and randomly swap it with any of the later elements for( int i = 0; i < n; i++ ) { exchange = i + (int)(Math.random() * (n - i)); temp = deck[i]; deck[i] = deck[exchange]; deck[exchange] = temp; } 21

 Searching through an array is an important operation  The simplest way to do so is just linear search: check every element in the array  Searching and sorting are really keys to all kinds of problems  We’ll cover both topics in depth in a few weeks 22

23

 Remember, you get no initialization with arrays of String s  If you try to access a non-existent element, the world will explode String[] stuff = new String[50]; String s = stuff[42]; // works fine int size = s.length(); // destroys world 24

 Accessing an element of an array that doesn’t exist will also kill your program int[] numbers = new int[100]; numbers[103] = 5; //crash System.out.println( numbers[-3]);//crash System.out.println( numbers[99]);//okay for( int i = 0; i <= 100; i++ ) numbers[i] = i; //crashes when i =

 Just as it is possible to make a one- dimensional list out of a single data type, it is also possible to make a table out of one data type  We can extend the arrays you know to have two dimensions with very similar syntax 26

 To declare a two dimensional array, we just use two sets of square brackets ( [][] ):  Doing so creates a variable that can hold a 2D array of int s  As before, we still need to instantiate the array to have a specific size: int [][] table; table = new int[5][10]; 27

 Like matrices, we usually visualize the first dimension as the rows and the second dimension as the columns Second Dimension First Dimension 28

 Let’s write a little code to put data into the table int [][] table = new int[5][10]; int label = 1; for( int i = 0; i < 5; i++ ) for( int j = 0; j < 10; j++ ) { table[i][j] = label; label++; } 29

 The result of that code is: Second Dimension First Dimension 30

 The ability to represent 2D data opens up lots of possibilities  We could store:  A chessboard  An image (where each number represents the color of a pixel)  A game of battleship  Or something even more interesting…  A matrix! 31

 I’m sure you’ve seen matrices before  Still, here’s a refresher: m rows n columns 32

 Addition can be done between two m x n matrices but not between matrices with mismatching dimensions  Just add the corresponding locations  You can also multiply an m x k matrix called A by a k x n matrix called B: only the common dimension must match  The result is an m x n matrix where the element in row i, column j is 33

 We could represent a chessboard as an 8 x 8 array of char s  Use the following encoding:  ‘P’ = pawn  ‘N’ = knight  ‘B’ = bishop  ‘R’ = rook  ‘Q’ = queen  ‘K’ = king  Use upper case characters for black pieces and lower case characters for white ones 34

 Imagine there is a pawn randomly set on the board and a queen of the opposite color on the board  Write a program to see if the queen can capture the pawn in the next move Q p 35

 Find the row and column location of both the queen and the pawn  The pawn is in danger if: 1. The queen and the pawn have the same row 2. The queen and the pawn have the same column 3. The queen and the pawn are on the same diagonal 36

 I lied to you  There are no such things as multidimensional arrays  They are all actually just arrays of arrays (of arrays…)  You are not required to create all of the dimensions at one time 37

 You could create each dimension separately and even specify different sizes  For example: int [][] pharma = new int[5][]; for( int i = 0; i < 5; i++ ) pharma[i] = new int[i + 1]; 38

 The resulting array will look like this: Columns Rows 39

 First of all, be warned that if you access an element that an array doesn’t have, your program will still crash  Ragged arrays do allow you to save some space  Imagine if some rows needed 10 elements and others needed 1,000,000  Usually, there’s no good reason to use ragged arrays, but sometimes there is…. 40

 It doesn’t have to stop at 2 dimensions!  You can have 3 or more  Here’s an example with 3 dimensions: int [][][] rubiksCube = new int[3][3][3]; int count = 1; for( int i = 0; i < rubiksCube.length; i++ ) for( int j = 0; j < rubiksCube[i].length; j++ ) for( int k = 0; j < rubiksCube[i][j].length; k++ ) { rubiksCube[i][j][k] = count; count++; } 41

 It looks like whatever you want it to  You can visualize it in 3D if you want  There are other techniques  It’s just a way to store data  It doesn’t actually look like anything inside the computer 42

 Sometimes you have data categorized in several different ways  For example, Purdue might keep some statistics according to Year, Gender, and Race  0 – Freshman  1 – Sophomore  2 – Junior  3 – Senior  Perfect candidate for a 3D array  0 – Male  1 – Female  0 – African American  1 – Asian  2 – Caucasian  3 – Other 43

 Too many brackets  Too much stuff  Total size used is the product of the length of all the dimensions  100 x 100 x 100 = 1,000,000  Hard to visualize, hard to imagine  Up as high as 4 is sometimes useful  Don’t go beyond 3 on a regular basis 44