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.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Creative Computing. \\ aims By the end of the session you will be able to: 1.Move objects around 2.Write simple interactive programs 3.Use the mouse position.
Variables Conditionals Boolean Expressions Conditional Statements How a program produces different results based on varying circumstances if, else if,
Addison Wesley is an imprint of © 2010 Pearson Addison-Wesley. All rights reserved. Chapter 10 Arrays and Tile Mapping Starting Out with Games & Graphics.
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.
Game with US Beginner Tutorial. Welcome!! Who I am What is Processing? Basic Coding Input Methods Images Classes Arrays.
© Calvin College, Being abstract is something profoundly different from being vague... The purpose of abstraction is not to be vague, but to create.
 Variables  What are they?  Declaring and initializing variables  Common uses for variables  Variables you get “for free” in Processing ▪ Aka: Built-in.
Lesson Four: More of the Same
Arrays. INTRODUCTION TO ARRAYS Just as with loops and conditions, arrays are a common programming construct and an important concept Arrays can be found.
 9: Arrays  Why?  What is an Array?  Declaring and Creating an Array  Initializing and Array  Array Operations  Array Examples  Arrays of Objects.
Processing Processing is a simple programming environment that was created to make it easier to develop visually oriented applications with an emphasis.
IAT 800 Lab 1: Loops, Animation, and Simple User Interaction.
Arrays  Writing a program that uses a large amount of information.  Such as a list of 100 elements.  It is not practical to declare.
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. 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.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 8 “Arrays”
Lecture 3 IAT 800. Sept 15, Fall 2006IAT 8002 Suggestions on learning to program  Spend a lot of time fiddling around with code –Programming is something.
Chapter 9 Introduction to Arrays
PROCESSING Animation. Objectives Be able to create Processing animations Be able to create interactive Processing programs.
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.
Programming for Artists ART 315 Dr. J. R. Parker Art/Digital Media Lab Lec 10 Fall 2010.
Lists in Python.
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.
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.
Review of ArT3 Programming Course David Meredith Aalborg University
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.
Review Recursion Call Stack. Two-dimensional Arrays Visualized as a grid int[][] grays = {{0, 20, 40}, {60, 80, 100}, {120, 140, 160}, {180, 200, 220}};
Lecture Set 9 Arrays, Collections and Repetition Part C - Random Numbers Rectangular and Jagged arrays.
Term 2, 2011 Week 1. CONTENTS Problem-solving methodology Programming and scripting languages – Programming languages Programming languages – Scripting.
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
Variables Art &Technology, 3rd Semester Aalborg University Programming David Meredith
Arrays. An array is a collection “The Dinner offers an array of choices.” In computer programming, an array is a collection of variables of the same data.
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
Arrays.
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.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
1 Arrays of Arrays An array can represent a collection of any type of object - including other arrays! The world is filled with examples Monthly magazine:
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
Continuous. Flow of Control Programs can broadly be classified as being –Procedural Programs are executed once in the order specified by the code varied.
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.
Arrays.
Arrays Chapter 12. Overview Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and arrays.
Chapter 8: Part 3 Collections and Two-dimensional 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.
Programming for Art: Arrays – 2D ART 315 Dr. J. R. Parker Art/Digital Media Lab Lec 16 Fall 2010.
© 2004 Pearson Addison-Wesley. All rights reserved7-1 Array review Array of primitives int [] count; count = new int[10]; Array of objects Grade [] cs239;
Review Objects – data fields – constructors – Methods Classes.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Variables. Something to mention… void setup(){ size(200, 200); background(255); smooth(); } void draw() { stroke(0); strokeWeight(abs(mouseX-pmouseX));
Loops. About the Midterm Exam.. Exam on March 12 Monday (tentatively) Review on March 5.
4. Java language basics: Function
Chapter 9 Arrays.
Based on lecture notes from Dr. Deepak Kumar of Brynmawr
Based on lecture notes from Dr. Deepak Kumar of Brynmawr
More programming with "Processing"
Chapter 8 Objects.
Chapter 9 Arrays.
Presentation transcript:

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 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

3 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

4 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!

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 5

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! 6 arrayOfInts [0] [1] [2] [3] [4] … [41] int

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! 7

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 8 int [] stuff = new int[3]; stuff[0] = 8; stuff[1] = 3; stuff[2] = 1; int [] stuff = { 8, 3, 1 };

Initializing with Iteration Rolling 5 dice (Yahtzee) Example The ‘hard’ way Using a while loop: 9 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] = (int)random(0,6); n = n + 1; } int n = 0; while (n < 5) { die[n] = (int)random(0,6); n = n + 1; }

Initializing with Iteration Rolling 5 dice (Yahtzee) Example The ‘hard’ way Using a for loop: 10 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); } for (int n = 0; n < 5; n++ ) { die[n] = (int)random(0,6); }

Length of the Array 11 Using a for loop to initialize an array: Note the use of values.length The array knows how long it is! float[] values = new float[6]; for (int i = 0; i < values.length; i++) values[i] = 0;

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]? 12 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) int[] xpos = new int[10];

Example: 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) 13 int[] xpos = new int[10]; int[] ypos = new int[10]; for (int i = 0; i < xpos.length; i++ ) { xpos[i] = 0; ypos[i] = 0; }

Arrays of Objects Using arrays to store multiple objects is a very powerful programming feature We will use the Car class and create an array of unique cars 14

The ‘Car’ Class Revisited class Car { color c; float xpos, ypos, xspeed; Car(color cp, float xposp, float yposp, float xspeedp) { c = cp; xpos = xposp; ypos = yposp; xspeed = xspeedp; } void display() { rectMode(CENTER); stroke(0); fill(c); rect(xpos,ypos,20,10); } void move() { xpos = xpos + xspeed; if (xpos > width) { xpos = 0; }

Step 1: Type Square Braces Array name semicolon Car[ ] cars ; Step 2: Array name Keyword Type Size semicolon cars = new Car [5] ; Or the ‘one-liner’ version Type [ ] Array name Keyword Type[Size] semi Car[ ] cars = new Car[5] ; 16 cars [0] [1] [2] [3] [4] [5] empty

Use a loop to fill up the array! void setup() { size(200,200); smooth(); for (_____________________________) { ___________________________________ } 17 Car color xpos ypos xspeed Car cars [0] [1] [2] [3] [4] [5] color xpos ypos xspeed color xpos ypos xspeed color xpos ypos xspeed color xpos ypos xspeed color xpos ypos xspeed

And let’s get them on the road! Use a loop to move and display them! void draw() { background(255); for (_____________________________) { ___________________ //call the move() function ___________________ //call the disp() function } 18

Interactive Objects (Stripe Example) 19 class Stripe{ float x; float w; boolean mouse; Stripe(float xp, float wp){ __________ } void display(){.... } void rollover(){.... }

Additional Processing Array features Processing provides a set of functions to help manage arrays: 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 20

append() String[] s = { "OH", "NY", "CA"}; s = append(s, "MA"); for (int i = 0; i < s.length; i++){ System.out.println(s[i]); } 21

Example: append() function Start with an array of one object. Each time the mouse is pressed, a new object is created and appended to the end of the original array. 22

23 class Ball { float x; float y; float speed; float w; Ball(float tempX, float tempY, float tempW) { x = tempX; y = tempY; w = tempW; speed = 0; } void gravity() { // Add gravity to speed speed = speed + gravity; } void move() { y = y + speed; if (y > height) { speed = speed * -0.95; y = height; } void display() { // Display the circle fill(175); stroke(0); ellipse(x,y,w,w); }

24 // Start with an array with just one ball.... void setup({ // Initialize the first ball... } void draw(){ // Display all the balls in the current array... } void mousePressed(){ // Create a new ball object at the mouse location and append it to the array.... }

Two-Dimensional Arrays 25 //One dimensional array int[] myArray = new int[10]; for (int i = 0; i < myArray.length; i++){ myArray[i] = 0; } //Two dimensional array int row = 10; int col = 15; int[] myArray = new int[row][col]; for (int i = 0; i < row; i++){ for (int j = 0; j < col; j++) { myArray[i] = 0; } //Using array initializer int[][] myArray = { {1, 2, 3, 4 }, {5, 6, 7, 8}, {9, 10, 11, 12} };

Example: Grayscale Image 26 size(200,200); int row = width; int col = height; float[][] myArray = new float[row][col]; // Initialize 2D array values for (int i = 0; i < row; i ++ ) { for (int j = 0; j < col; j ++ ) { myArray[i][j] = random(255); } // Draw points for (int i = 0; i < row; i ++ ){ for (int j = 0; j < col; j ++ ) { stroke(myArray[i][j]); point(i,j); }