BIT115: Introduction to Programming

Slides:



Advertisements
Similar presentations
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Advertisements

Lecture 17 Instructor: Craig Duckett Passing & Returning Arrays.
CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 10 / 04 / 2006 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 03 / 03 / 2008 Instructor: Michael Eckmann.
Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays.
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 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.
BIT115: Introduction to Programming
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
Lecture 11 Instructor: Craig Duckett Instance Variables.
Data Structures & Algorithms CHAPTER 2 Arrays Ms. Manal Al-Asmari.
BIT115: Introduction to Programming
Chapter VII: Arrays.
CSC 211 Java I for loops and arrays.
Computer Organization and Design Pointers, Arrays and Strings in C
User-Written Functions
Array Review CS 139 – November 28, 2007.
BIT 115: Introduction To Programming
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Lecture 5 D&D Chapter 6 Arrays and ArrayLists Date.
BIT115: Introduction to Programming
Chapter 7 Part 1 Edited by JJ Shepherd
COSC 220 Computer Science II
Lecture 10: More on Methods and Scope
Repetition-Counter control Loop
Arrays in C.
BIT115: Introduction to Programming
CSC 253 Lecture 8.
CSC 142 Computer Science II
BIT115: Introduction to Programming
CSC141 Computer Science I Zhen Jiang Dept. of Computer Science
Arrays An Array is an ordered collection of variables
Chapter 6 Arrays Solution Opening Problem
CSC 253 Lecture 8.
Building Java Programs
Array Review CS 139 – November 28, 2007.
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.
int [] scores = new int [10];
Java Programming Arrays
Defining methods and more arrays
Object Oriented Programming in java
BIT115: Introduction to Programming
Cs212: Data Structures Computer Science Department Lecture 2: Arrays.
Topics discussed in this section:
CS2011 Introduction to Programming I Arrays (I)
Announcements Lab 7 due Wednesday Assignment 4 due Friday.
int [] scores = new int [10];
slides created by Ethan Apter
Announcements Lab 6 was due today Lab 7 assigned this Friday
OBJECT ORIENTED PROGRAMMING II LECTURE 13_2 GEORGE KOUTSOGIANNAKIS
Building Java Programs
Single-Dimensional Arrays chapter6
OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS
Array Review CS 139 – November 28, 2007.
Dr. Sampath Jayarathna Cal Poly Pomona
Arrays in Java.
Suggested self-checks: Section 7.11 #1-11
BIT115: Introduction to Programming
Data Structures & Algorithms
Building Java Programs
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Arrays, Part 1 of 2 Topics Definition of a Data Structure
How do you do the following?
Java Coding 6 David Davenport Computer Eng. Dept.,
SPL – PS2 C++ Memory Handling.
Week 7 - Monday CS 121.
Presentation transcript:

BIT115: Introduction to Programming Lecture 17 Instructor: Craig Duckett Passing & Returning Arrays

Assignment Dates (By Due Date) Assignment 1 (LECTURE 5) GRADED! Section 1: Monday, January 22nd Assignment 2 (LECTURE 8) GRADED! Section 1: Wednesday, January 31st Assignment 1 Revision (LECTURE 10) GRADED! Section 1: Wednesday, February 7th Assignment 2 Revision (LECTURE 12) GRADED! Section 1: Wednesday, February 14th Assignment 3 (LECTURE 13) GRADED! Section 1: Wednesday, February 21st Assignment 3 Revision (LECTURE 16) GRADED! Section 1: Monday, March 5th Assignment 4 (LECTURE 18) NO REVISION! Section 1: Monday, March 12th The Fickle Finger of Fate

Today’s Topics Arrays (Recap) Arrays as Parameters Returning an Array (we'll cover again in next class) Assignment 4 Basic and Advanced Overview WALK-THROUGH: ICE

And now ... The Quiz

RECAP: Arrays 11 22 33 44 55 66

Recap: Arrays What is an Array? Primitive variables are designed to hold only one value at a time. Arrays allow us to create a collection of like values that are indexed. An array can store any type of data but only one type of data at a time. An array is a list of data elements.

Recap: Arrays Let’s pretend we have a list of five (5) grades we’d like to store in memory. We could declare the value for each grade one at a time like this: int grade1 = 100; int grade2 = 89; int grade3 = 96; int grade4 = 100; int grade5 = 98; The five grades are then stored in memory wherever there happens to be room. The “address” in memory where each grade is store is it’s declared name (e.g., grade1) and the data stored there is the integer value itself (e.g., 100). To access each grade number and do something with it (e.g., display it), we’d call up the memory location by its assigned (declared) name: System.out.println("The first grade is: " + grade1);

Recap: Arrays In memory, the array elements are mostly stored in sequential order We could, however, simplify our work by doing the same thing with an array. Instead of declaring each integer one at a time, we could declare the whole shebang at the same time, like so: Even though you declared an array with [5] elements, the “count” of the elements starts with [0] grades = new int[5]; Initially, this creates a location in memory to hold the five elements that make up the array, automatically initializing each of those storage spaces to zero. All you have to do now is fill those elements. grades[0] = 100; grades[1] = 89; grades[2] = 96; grades[3] = 100; grades[4] = 98; Of course, you could have also declared and set them up like this all in one step: int[ ] grades = { 100, 89, 96, 100, 98 };

Another way of thinking about it in the abstract … int [] grades = new int[5]; grades[0] = 100; grades[1] = 89; grades[2] = 96; grades[3] = 100; grades[4] = 98; The numbers inside the square braces [ ] are the "slot" numbers The numbers to the right of the assignment operator '=' are the data values going into the slots

Another way of thinking about it in the abstract … The numbers inside the square braces [ ] are the "slot" numbers The numbers to the right of the assignment operator '=' are the data values going into the slots

Length (size declarator) int [] grades = new int[5]; grades[0] = 100; grades[1] = 89; grades[2] = 96; grades[3] = 100; grades[4] = 98; Length (size declarator) int [] grades = new int[5]; grades[0] = 100; grades[1] = 89; grades[2] = 96; grades[3] = 100; grades[4] = 98; int [] grades = new int[5]; grades[0] = 100; grades[1] = 89; grades[2] = 96; grades[3] = 100; grades[4] = 98; Index Subscripts

Recap: Arrays Comparing individual integer declarations to an array of integers: int grade1 = 100; int grade2 = 89; int grade3 = 96; int grade4 = 100; int grade5 = 98; In memory, the individual integers are stored wherever there happens to be an available space System.out.println("The first grade is: " + grade1); grades = new int[5]; grades[0] = 100; grades[1] = 89; grades[2] = 96; grades[3] = 100; grades[4] = 98; In memory, the array elements are mostly stored in sequential order System.out.println("The first grade is: " + grade[0]);

Recap: Arrays Because array elements are numbered sequentially, it is a no-brainer to either populate the data in the array, or to call up and access the data in the array using Loops Scanner keyboard = new Scanner(System.in); // Original code thanks to Kamran Majidimehr! int counter = 0; int arraylength = 0; System.out.println("How many grades would you like to enter?"); arraylength = keyboard.nextInt(); System.out.println("You have indicated that you'd like to enter " + arraylength + " grades.\nPlease enter grades now, one at a time."); int countdown = arraylength; double average = 0; double grades[] = new double [arraylength]; while( counter < arraylength ) { grades[counter] = keyboard.nextDouble(); System.out.println("(" + (counter + 1) + ") You entered: " + grades[counter] + " [There are " + (countdown - 1) + " grades remaining]"); counter++; countdown--; } With loops you can either enter data manually when prompted or enter data automatically based on the particular requirements of the data going into the array

Arrays as Parameters 11 22 33 44 55 66 PASS 11 22 33 44 55 66

Arrays are known as "Reference Types" Now that we have discussed the syntax for working with arrays, we should examine why array types are known as reference types. As we discussed earlier in the quarter, all the Java primitive types have well-defined standard sizes, so all primitive values can be stored in a fixed amount of memory (between 1 and 8 bytes, depending on the data type). But array types do not have a standard size, and they often require quite a bit more memory than eight bytes. For this reason, Java does not work with arrays directly. Instead, it works with references to arrays. Because Java handles arrays by reference, array types are known as reference types. In contrast, Java handles values of the primitive types directly, that is to say by value. A reference to an array is simply some fixed-size value that refers to the array in some way. When you assign an array to this value, you are actually setting that value to hold a reference to that array. Similarly, when you pass an array to a method, what really happens is that the method is given a reference to the array through which it can work with the array in some way. Typically, this reference is the memory address at where the array is stored. Let's have a look at what this all means in the grand scheme of things…

ANALOGY: Storefront and Warehouse

ANALOGY: Storefront and Warehouse

ANALOGY: Storefront and Warehouse 43011 43013 43015 43017 43019 My products are stored In Warehouse # 43015

Arrays as Parameters shortArray created longArray created Passing shortArray by name Passing longArray by name

Arrays as Parameters class ArrayHelper - PrintArray method main - shortArray - longArray

Arrays as Parameters Passing an array as a parameter This method has been setup to expect an array to be passed to it, and will use the array space called arrayName to point to the passed array data when it is.

Arrays as Parameters

Arrays as Parameters

Arrays as Parameters Name Only Name Only

Arrays as Parameters Passing an array to a method behaves differently than passing a primitive data type. The array values aren't copied directly to the method, but rather a reference to the address where those values can be found. 1, 3, 5 But how does this really work in memory? How does the method actually know which array to point to and use?

Arrays as Parameters Is allocated when Is allocated when Don’t worry about any of this memory, stack, or heap information as it won’t show up on the Final Exam  Is allocated when program loads; “temporary” Is allocated when program runs; “persistent”

Arrays as Parameters shortArray 1, 3, 5 longArray 1, 2, 3, 5, 7 (1) PrintArray method is called and and checks name in parameter which is a named storage space in the memory heap (2) PrintArray than copies the array by its address and then plugs it through the arrayName placeholder where it might be used by the method. So, when you pass an array as a parameter, you’re actually passing a copy of the address of where the array data is located. Depending how you set up the method to work with the array, the original array data may or may not be changed. Let's have a look at what this "may or may not" means…

AN ABSTRACTION: How Does This Look In Memory? Before either the shortArray or longArray array is passed by name, the arrayName array set up in the method doesn't have a "working" address or value per se, since it will be initialized from the referenced memory address of the name of the array that it is passed.

AN ABSTRACTION: How Does This Look In Memory? Although the name of the array that is being passed is a "reference" it is still "passing by value" except in this case that value is a copy of the address of the named array.

Arrays as Parameters EXAMPLES: PassArrayChangeValues.java import java.util.*; class Change extends Object { public void AddFives(int arrayName[]) { for(int j = 0; j < arrayName.length; j++) { arrayName[j]+=5; // Same as: arrayName[j] = arrayName[j] + 5; } } } public class PassArrayChangeValues extends Object { public static void main(String[] args) { Change DoIt = new Change(); int [] myArray = new int[5]; myArray[0] = 2; myArray[1] = 4; myArray[2] = 6; myArray[3] = 8; myArray[4] = 10; System.out.println("myArray contains:"); for(int i = 0; i < myArray.length; i++) { System.out.println("Slot " + (i + 1) + " is: " + myArray[i]); } DoIt.AddFives(myArray); System.out.println(); System.out.println("myArray NOW contains:"); for(int i = 0; i < myArray.length; i++) { System.out.println("Slot " + (i + 1) + " is: " + myArray[i]); } } } EXAMPLES: PassArrayChangeValues.java ArrayTester.java

Returning an Array I’m going to go over the Lecture 18 part of this now, and repeat it again on Monday where you will do the ICES for Returning an Array at that time.

Passing and Returning Arrays Passing Arrays as Arguments Arrays are objects. Their references can be passed to methods like any other object reference variable. 5 10 15 20 25 Address showArray(numbers); 30 35 40 public static void showArray(int[] array) { for (int i = 0; i < array.length; i++) System.out.print(array[i] + " "); } Example: PassArray.java

Passing and Returning Arrays We just learned how you could pass an array into a method. Now we’re going to take this to the next step to learn how you can return an array from a method. A method can return a reference to an array. To do so, the return type of the method must be declared properly. For example, look at the following method definition: public static double[] getArray() // <-- No parameters called { double[] array = {1.2, 2.3, 4.5, 6.7, 8.9} return array; } double is the return type return sends back a double The getArray method is a public static method that returns an array of doubles. See example: ReturnArray.java

Assignment 4 Basic and Advanced BASIC is Robot related and includes a few comments and hints. It will create a Histogram with Things and a print out using asterisks. It does not interact wit a User. ADVANCED is Non-Robot related and includes hardly any hints. It will create a “Guess a Number” game and interact with a User.

Assignment 4 Basic (Demo) NOTE: You will need to pass an array as a parameter to “solve” Assignment 4 Basic, but you DO NOT need to return an array. After today’s ICE you will have learned everything you need to successfully complete Assignment 4 Basic

Assignment 4 Advanced A look at the Advanced “Guessing Game” assignment… NOTE: You do NOT need to pass an array as a parameter to “solve” Assignment 4 Advanced, and you DO NOT need to return an array, although you could do it that way if you wanted to. You WILL need to return a Boolean ‘true’ or ‘false’ however in some of your methods as well as return the number guessed to be successful with Assignment 4 Advanced.

ICE: Arrays as Parameters I’m going to walk-through the building of the PrintArray method for ICE PART 1 ICE_18_PrintArray.java

import java.util.*; class ArrayHelper extends Object { public void PrintArray( int[] arrayName) // Whatever array is passed in main will populate arrayName here { // Use a for loop here that checks the count against the length of arrayName, then iterates if less than length // HINT: You might want to check out the SOLUTIONS to previous lecture ICE exercises // for ( ?? ; ?? ; ??) { // print out the array } } } public class ICE_18_PrintArray extends Object { public static void main(String[] args) { ArrayHelper arrayTester = new ArrayHelper(); // We're creating the two arrays in two different ways: // the shortArray has 3 locations and the longArray has 5, but in the longArray // we can shorten the way we assign numbers using the single line "array literal" method int [] shortArray; // Instantiate the shortArray here with 3 slots holding the three numbers: 1, 3, 5 // Add number to slot 0 // Add number to slot 1 // Add number to slot 2 int [] longArray; // fill the longArray as an "array literal" with five numbers: 1, 2, 3, 5, 7 // print out both the short and long arrays System.out.println("\nThe Short Array: "); arrayTester.PrintArray(shortArray); // Passing the shortArray to the PrintArray() method System.out.println("\nThe Long Array: "); arrayTester.PrintArray(longArray); // Passing the longArray to the PrintArray() method } }

import java.util.*; class ArrayHelper extends Object { public void PrintArray( int[] arrayName) // Whatever array is passed in main will populate arrayName here { // Use a for loop here that checks the count against the length of arrayName, then iterates if less than length // HINT: You might want to check out the SOLUTIONS to previous lecture ICE exercises // for ( ?? ; ?? ; ??) { // print out the array } } } public class ICE_18_PrintArray extends Object { public static void main(String[] args) { ArrayHelper arrayTester = new ArrayHelper(); // We're creating the two arrays in two different ways: // the shortArray has 3 locations and the longArray has 5, but in the longArray // we can shorten the way we assign numbers using the single line "array literal" method int [] shortArray = new int [3]; // Instantiate the shortArray here with 3 slots holding the three numbers: 1, 3, 5 shortArray[0] = 1; shortArray[1] = 3; shortArray[3] = 5; int [] longArray; // fill the longArray as an "array literal" with five numbers: 1, 2, 3, 5, 7 // print out both the short and long arrays System.out.println("\nThe Short Array: "); arrayTester.PrintArray(shortArray); // Passing the shortArray to the PrintArray() method System.out.println("\nThe Long Array: "); arrayTester.PrintArray(longArray); // Passing the longArray to the PrintArray() method } }

import java.util.*; class ArrayHelper extends Object { public void PrintArray( int[] arrayName) // Whatever array is passed in main will populate arrayName here { // Use a for loop here that checks the count against the length of arrayName, then iterates if less than length // HINT: You might want to check out the SOLUTIONS to previous lecture ICE exercises // for ( ?? ; ?? ; ??) { // print out the array } } } public class ICE_18_PrintArray extends Object { public static void main(String[] args) { ArrayHelper arrayTester = new ArrayHelper(); // We're creating the two arrays in two different ways: // the shortArray has 3 locations and the longArray has 5, but in the longArray // we can shorten the way we assign numbers using the single line "array literal" method int [] shortArray = new int [3]; // Instantiate the shortArray here with 3 slots holding the three numbers: 1, 3, 5 shortArray[0] = 1; shortArray[1] = 3; shortArray[3] = 5; int [] longArray = {1, 2, 3, 5, 7}; // print out both the short and long arrays System.out.println("\nThe Short Array: "); arrayTester.PrintArray(shortArray); // Passing the shortArray to the PrintArray() method System.out.println("\nThe Long Array: "); arrayTester.PrintArray(longArray); // Passing the longArray to the PrintArray() method } }

import java.util.*; class ArrayHelper extends Object { public void PrintArray( int[] arrayName) // Whatever array is passed in main will populate arrayName here { // Use a for loop here that checks the count against the length of arrayName, then iterates if less than length // HINT: You might want to check out the SOLUTIONS to previous lecture ICE exercises for( int count = 0; count < arrayName.length; count++) { System.out.println( count + ") Number: " + arrayName[count]); } } } public class ICE_18_PrintArray extends Object { public static void main(String[] args) { ArrayHelper arrayTester = new ArrayHelper(); // We're creating the two arrays in two different ways: // the shortArray has 3 locations and the longArray has 5, but in the longArray // we can shorten the way we assign numbers using the single line "array literal" method int [] shortArray = new int [3]; // Instantiate the shortArray here with 3 slots holding the three numbers: 1, 3, 5 shortArray[0] = 1; shortArray[1] = 3; shortArray[3] = 5; int [] longArray = {1, 2, 3, 5, 7}; // print out both the short and long arrays System.out.println("\nThe Short Array: "); arrayTester.PrintArray(shortArray); // Passing the shortArray to the PrintArray() method System.out.println("\nThe Long Array: "); arrayTester.PrintArray(longArray); // Passing the longArray to the PrintArray() method } }

count arrayName 1, 3, 5 shortArray longArray import java.util.*; class ArrayHelper extends Object { public void PrintArray( int[] arrayName) { for( int count = 0; count < arrayName.length; count++) { System.out.println( count + ") Number: " + arrayName[count]); } } } public class ICE_18_PrintArray extends Object { public static void main(String[] args) { ArrayHelper arrayTester = new ArrayHelper(); // We're creating the two arrays in two different ways: // the shortArray has 3 locations and the longArray has 5, but in the longArray // we can shorten the way we assign numbers using the single line "array literal" method int [] shortArray = new int [3]; // Instantiate the shortArray here with 3 slots holding the three numbers: 1, 3, 5 shortArray[0] = 1; shortArray[1] = 3; shortArray[3] = 5; int [] longArray = {1, 2, 3, 5, 7}; // print out both the short and long arrays System.out.println("\nThe Short Array: "); arrayTester.PrintArray(shortArray); System.out.println("\nThe Long Array: "); arrayTester.PrintArray(longArray); } } count arrayName 1, 3, 5 shortArray longArray

In-Class Exercises: Arrays as Parameters