Lesson Four: More of the Same

Slides:



Advertisements
Similar presentations
Addison Wesley is an imprint of © 2010 Pearson Addison-Wesley. All rights reserved. Chapter 10 Arrays and Tile Mapping Starting Out with Games & Graphics.
Advertisements

Lesson One: The Beginning Chapter 3: Interaction Learning Processing: by Daniel Shiffman Presentation by Donald W. Smith Graphics from text.
Objects. 2 Object Oriented Programming (OOP) OOP is a different way to view programming Models the real world A different view than Structured programming.
 Functions breakdown: Functions purpose Modularity Declaring and defining a function Calling a function Parameter passing Returning a value Reusability.
 Variables  What are they?  Declaring and initializing variables  Common uses for variables  Variables you get “for free” in Processing ▪ Aka: Built-in.
Variables Conditionals Loops The concept of Iteration Two types of loops: While For When do we use them? Iteration in the context of computer graphics.
Chapter 10 Introduction to Arrays
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
 9: Arrays  Why?  What is an Array?  Declaring and Creating an Array  Initializing and Array  Array Operations  Array Examples  Arrays of Objects.
 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.
Introduction to Computers and Programming Lecture 15: Arrays Professor: Evan Korth New York University.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
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.
CS 106 Introduction to Computer Science I 02 / 28 / 2007 Instructor: Michael Eckmann.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 8 “Arrays”
 2003 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Arrays Introduction to Computers and Programming in.
Lesson Three: Organization
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
Chapter 9 Introduction to Arrays
CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
PROCESSING Animation. Objectives Be able to create Processing animations Be able to create interactive Processing programs.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Review Blocks of code {.. A bunch of ‘statements’; } Structured programming Learning Processing: Slides by Don Smith 1.
Classes / Objects An introduction to object-oriented programming.
Lists in Python.
11 Finding Winners Using Arrays Session 8.2. Session Overview  Find out how the C# language makes it easy to create an array that contains multiple values.
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.
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.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
Variables and Functions. Open your Encoder program Let’s begin by opening the “Labyrinth Auto Straight” code. Save this file as Labyrinth with variables.
By Melissa Dalis Professor Susan Rodger Duke University June 2011 Multiplication Table.
Lecture Set 9 Arrays, Collections and Repetition Part C - Random Numbers Rectangular and Jagged arrays.
11 Adding Tomato Targets Session Session Overview  We now have a game which lets a player bounce a piece of cheese on a bread bat  Now we have.
Arrays Art &Technology, 3rd Semester Aalborg University Programming David Meredith
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!
CIS 3.5 Lecture 2.2 More programming with "Processing"
Lesson Two: Everything You Need to Know
Objects. The Heart of the Matter - The "Black Box" Object-oriented software is all about objects. An object is a "black box" which receives and sends.
Lesson Two: Everything You Need to Know
Lesson 3: Arrays and Loops. Arrays Arrays are like collections of variables Picture mailboxes all lined up in a row, or storage holes in a shelf – You.
1 One Dimensional Arrays Chapter 11 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
Tutorial for Arrays and Lists. Description This presentation will cover the basics of using Arrays and Lists in an Alice world It uses a set of chickens.
CHAPTER 14 Classes, Objects, and Games XNA Game Studio 4.0.
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.
Review Array – int[] diameters = new int[10]; – diameters[0], diameters[2], diameters[9] – diameters.length Indexing starts at 0 A way to have a collection.
Week 9 - Wednesday.  What did we talk about last time?  2D arrays  Queen attacking pawn example  Started Game of Life.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Arrays Chapter 12. Overview Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and arrays.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
11 Adding a Bread Bat Session Session Overview  We have created a cheese sprite that bounces around the display  We now need to create a bread.
Programming for Art: Arrays – 2D ART 315 Dr. J. R. Parker Art/Digital Media Lab Lec 16 Fall 2010.
Clue Paths. Memory Alias Review Remember that it’s possible for two unique variables to point to the same memory location myList MyClass mc 0x100 someFn.
Review Objects – data fields – constructors – Methods Classes.
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.
Arrays. 2 Why do we care (about arrays)? What if you have a whole bunch of cars (or aliens or balls or ???) bouncing around the screen? How do we keep.
Variables. Something to mention… void setup(){ size(200, 200); background(255); smooth(); } void draw() { stroke(0); strokeWeight(abs(mouseX-pmouseX));
Chapter 8 Objects.
Lesson Two: Everything You Need to Know
Chapter 9 Arrays.
Arrays, For loop While loop Do while loop
Chapter 8 Objects.
MSIS 655 Advanced Business Applications Programming
Presentation transcript:

Lesson Four: More of the Same Chapter 9: Arrays Learning Processing Daniel Shiffman Presentation by Donald W. Smith Graphics from text

Lesson Four: More of the Same 9: Arrays Why? What is an Array? Declaring and Creating an Array Initializing and Array Array Operations Array Examples Arrays of Objects Learning Processing: Slides by Don Smith

Why do we care (about arrays)? What if you have a whole bunch of cars (or aliens or balls or ???) bouncing around the screen? How do we keep track of where each one is? int car1X, car1Y, car2X, car2Y, car3X, car3Y…… How about keeping them in a ‘table’ or a ‘grid’ CarX table: Each ‘column’ has a number You can refer to CarX table, column 3 for Car3… Note that all of the values in the row must be the same data type 1 2 3 4 5 6 7 8 9 10 Learning Processing: Slides by Don Smith

When to use an Array Any time a program requires multiple instances of similar data, it might be time to use an array. For example, an array can be used to store: The scores of four players in a game A selection of 10 colors in a design program A list of fish objects in an aquarium simulation The days per month in a scheduling program Learning Processing: Slides by Don Smith

What is an array? A variable is a named location in memory. An array is a named set of locations in memory A ‘list’ of variables Each element of the list has a number called an ‘index’ Starts at 0! Learning Processing: Slides by Don Smith

Why start at 0? Why not 1? Which of the following is why arrays start at 0? A) Because programmers think that way B) Because I say so C) So that programmers can make ‘the big bucks’ D) So you can use loops easily to ‘walk’ the array Here’s a preview of adding up all the ‘votes’: int sumArray(int size) { int sum = 0; for (int c = 0; c < size; c++) { sum = sum + votes[c]; // huh? [ ]? } return sum; Learning Processing: Slides by Don Smith

How to Declare an array (Step 1) Create the array variable (with the name and type) Make a named ‘list’ with the following parts: Type Square Braces Array name semicolon int [ ] arrayOfInts ; You are ‘declaring’ that There is an array named arrayOfInts The elements inside are of type int You have not (YET) declared how many are in inside Other Rules: Arrays can be declared anywhere you can declare a variable Do not use ‘reserved’ words or already used names Learning Processing: Slides by Don Smith

How to Create an array (Step 2) Reserve memory for all of the elements in the list: Array name Keyword Type Size semicolon arrayOfInts = new int [42] ; You are reserving memory for: The array named arrayOfInts Needs storage for [42] elements the size of type int Now you (and the compiler) know how many are in inside You cannot change the size after you declare it! arrayOfInts [0] [1] [2] [3] [4] … [41] int int int int int int Learning Processing: Slides by Don Smith

Two Steps on one line: Declare and Create at the same time: Type Braces Array name Keyword Type Size semi int [] arrayOfInts = new int [42] ; You are ‘declaring’ that There is an array named arrayOfInts The elements inside are of type int You are reserving memory for the array Needs storage for [42] elements the size of type int Note that the size cannot be changed, so you should make enough room when you start! Learning Processing: Slides by Don Smith

Exercise 9-3: Write the declarations for: Declare the array variable (step 1) for these: Learning Processing: Slides by Don Smith

Exercise 9-3: Write the declarations for: Declare the array variable (step 1) for these: // type [] arrayName ; int [] arrayOfInts; float [] hundredFloats; Zoog [] zoogArmy; Learning Processing: Slides by Don Smith

Exercise 9-3: Write the declarations for: Declare storage (step 2) for the following: Learning Processing: Slides by Don Smith

Exercise 9-3: Write the declarations for: Declare storage (step 2) for the following: // arrayName = new type[size]; arrayOfInts = new int[30]; hundredFloats = new float[100]; zoogArmy = new Zoog[56]; Learning Processing: Slides by Don Smith

Exercise 9-3: Write the declarations for: Both Steps 1 and 2 on the same line: Learning Processing: Slides by Don Smith

Exercise 9-3: Write the declarations for: Both Steps 1 and 2 on the same line: // type [] arrayName = new type[size]; int [] arrayOfInts = new int[30]; float [] hundredFloats = new float[100]; Zoog [] zoogArmy = new Zoog[56]; Learning Processing: Slides by Don Smith

Exercise 9-4: What’s wrong with these? May be valid, maybe not! Learning Processing: Slides by Don Smith

Initializing an Array The ‘long’ way The one-liner way: The compiler counts the number of elements (3) Sets the size automatically! Fills the contents with the values inside the { }; Values are separated by commas int [] stuff = new int[3]; stuff[0] = 8; stuff[1] = 3; stuff[2] = 1; int [] stuff = { 8, 3, 1 }; Learning Processing: Slides by Don Smith

Initializing with Iteration Rolling 5 dice (Yahtzee) Example The ‘hard’ way Using a while loop: int[] die = new int[5]; die[0] = (int)random(0,6); die[1] = (int)random(0,6); die[2] = (int)random(0,6); die[3] = (int)random(0,6); die[4] = (int)random(0,6); int n = 0; while (n < 5) { die[n] = random(0,6); n = n + 1; } Learning Processing: Slides by Don Smith

Initializing with Iteration Rolling 5 dice (Yahtzee) Example The ‘hard’ way Using a for loop: int[] die = new int[5]; die[0] = (int)random(0,6); die[1] = (int)random(0,6); die[2] = (int)random(0,6); die[3] = (int)random(0,6); die[4] = (int)random(0,6); for (int n = 0; n < 5; n++ ) { die[n] = (int)random(0,6); } Learning Processing: Slides by Don Smith

Exercise 9-7: Loop/Array example: Using a for loop to initialize an array: Note the use of values.length The array knows how long it is! Now write code to square each entry: float[] values = new float[6]; for (int i = 0; i < values.length; i++) values[i] = 0; int [] nums = { 5, 4, 2, 7, 6, 8, 5, 2, 6, 14 }; Learning Processing: Slides by Don Smith

Exercise 9-7: Loop/Array continued: int [] nums = { 5, 4, 2, 7, 6, 8, 5, 2, 6, 14 }; Learning Processing: Slides by Don Smith

Walking off the end of the array… A very common problem is trying to access an element in the array that doesn’t exist: Remember that we start at element 0 What is the index of the last element? ______ What happens if we try to access element [10]? Try it and see! int[] xpos = new int[10]; for (int i = 0; i <= 10; i++ ) { xpos[i] = 0; } Exception in thread "Animation Thread" java.lang.ArrayIndexOutOfBoundsException: 10 at OutOfBounds.setup(OutOfBounds.java:21) Learning Processing: Slides by Don Smith

Arrays Lab: Preliminary to The Snake Declare and initialize two ‘global’ arrays: Initialize them in setup() Each time the mouse is clicked, store the mouseX and mouseY into the next available spot in the array (fill from left to right) Each time through draw, display a line between each location saved in the array. int[] xpos = new int[10]; int[] ypos = new int[10]; for (int i = 0; i < xpos.length; i++ ) { xpos[i] = 0; ypos[i] = 0; } Learning Processing: Slides by Don Smith

Additional Processing Array features Processing provides a set of functions to help manage arrays (covered in 9.9): shorten() concat() -- Puts two arrays together subset() append() splice() expand() – Make an array larger in size! sort() – Sort all the elements in the array reverse() – Reverse the order of all elements Learning Processing: Slides by Don Smith

Arrays of Objects Using arrays to store multiple objects is a very powerful programming feature We will use the Car class (from Chapter 8), and create a screen full of unique cars Learning Processing: Slides by Don Smith

The ‘Car’ Class Revisited class Car { // Define a class below the rest of the program. color c; // Variables. float xpos, ypos, xspeed; // Constructor with three parameters Car(color c_, float xpos_, float ypos_, float xspeed_) { c = c_; xpos = xpos_; ypos = ypos_; xspeed = xspeed_; } void display() { // Function. // The car is just a square rectMode(CENTER); stroke(0); fill(c); rect(xpos,ypos,20,10); void move() { // Function. xpos = xpos + xspeed; if (xpos > width) { xpos = 0; }

Make the parking lot… Step 1: Make the reference to the lot Type Square Braces Array name semicolon Car [ ] lot ; Step 2: Make the parking spots Array name Keyword Type Size semicolon lot = new Car [100] ; Or the ‘one-liner’ version Type [ ] Array name Keyword Type[Size] semi Car [ ] lot = new Car[100] ; lot [0] [1] [2] [3] [4] [5] empty empty empty empty empty empty Learning Processing: Slides by Don Smith

Now Let’s play General Motors! Use a loop to fill up the parking lot! void setup() { size(200,200); smooth(); for (int i = 0; i < lot.length; i ++ ) { lot[i] = new Car(color(i*2),0,i*2,i/20.0); } lot [0] [1] [2] [3] [4] [5] Car color xpos ypos xspeed Car Car Car Car Car color xpos ypos xspeed color xpos ypos xspeed color xpos ypos xspeed color xpos ypos xspeed color xpos ypos xspeed Learning Processing: Slides by Don Smith

And let’s get them on the road! Use a loop to move and display them! void draw() { background(255); for (int i = 0; i < cars.length; i ++ ) { cars[i].move(); cars[i].display(); } Learning Processing: Slides by Don Smith

Summary Arrays make it easier to store ‘groups’ or ‘lists’ 1) Must be exactly the same type inside 2) Can be any length, but they do have an end! 3) Each item has a index number (starting from 0) Setting up arrays is a two step process: 1) Declare the array (set name, type inside) 2) Create the array (sets length, uses ‘new’) Can be done on one line though! Arrays can be initialized: { 1, 17, 28 } For loops and arrays are natural partners Initializing all elements ‘Walking’ through the array Access array elements with [index] Learning Processing: Slides by Don Smith