Lecture 17 Instructor: Craig Duckett Passing & Returning Arrays.

Slides:



Advertisements
Similar presentations
1 Various Methods of Populating Arrays Randomly generated integers.
Advertisements

Arrays I Savitch Chapter 6.1: Introduction to Arrays.
Arrays. What is an array An array is used to store a collection of data It is a collection of variables of the same type.
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
Arrays Chapter 6 Chapter 6.
Loops Notes adapted from Dr. Flores. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while”
Arrays CS Feb Announcements Exam 1 Grades on Blackboard Project 2 scores: end of Class Project 4, due date:20 th Feb –Snakes & Ladders Game.
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.
Lecture 15 Arrays: Part 1 COMP1681 / SE15 Introduction to Programming.
ECE122 L13: Arrays of Objects March 15, 2007 ECE 122 Engineering Problem Solving with Java Lecture 13 Arrays of Objects.
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.
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
Java Unit 9: Arrays Declaring and Processing Arrays.
Lecture 10 Instructor: Craig Duckett. Assignment 2 Revision TONIGHT DUE TONIGHT Wednesday, August 5 th Assignment 3 NEXT DUE NEXT Monday, August 10 th.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.
Week101 APCS-A: Java November 8, week102 Java Packages All Java classes are grouped into libraries (or packages)  String is part of the java.lang.
One Dimensional Array. Introduction to Arrays Primitive variables are designed to hold only one value at a time. Arrays allow us to create a collection.
Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Lecture 10 Instructor: Craig Duckett Lecture 10 is in Lecture 11 Folder.
ArrayList, Multidimensional Arrays
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 Array 8-1 Outline  Extra material  Array of Objects  enhanced-for Loop  Class Array  Passing Arrays as Arguments to Methods  Returning Arrays.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
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.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 15: More-Advanced Concepts.
Review of ICS 102. Lecture Objectives To review the major topics covered in ICS 102 course Refresh the memory and get ready for the new adventure of ICS.
1 Arrays An array is a collection of data values, all of which have the same type. The size of the array is fixed at creation. To refer to specific values.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
Method Overloading  Methods of the same name can be declared in the same class for different sets of parameters  As the number, types and order of the.
CS 139-Programming Fundamentals Lecture 11B - Arrays Adapted from a presentation by Dr. Rahman Fall 2014.
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.
CS 106 Introduction to Computer Science I 03 / 02 / 2007 Instructor: Michael Eckmann.
CS 31 Discussion, Week 5 Faisal Alquaddoomi, Office Hours: BH 2432, MW 4:30-6:30pm, F 12:00-1:00pm (today)
8-1 Chapter-7 Part1 Introduction to Arrays –Array Types –Creating/Declaring Arrays –Initializing Arrays –Processing Array Contents –Passing Arrays as Arguments.
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.
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.
BIT115: Introduction to Programming
Two Dimensional Arrays Found in chapter 8, Section 8.9.
int [] scores = new int [10];
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];
Week 6 - Friday.  What did we talk about last time?  Loop examples.
Midterm Review Tami Meredith. Primitive Data Types byte, short, int, long Values without a decimal point,..., -1, 0, 1, 2,... float, double Values with.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Lecture 11 Instructor: Craig Duckett Instance Variables.
Data Structures & Algorithms CHAPTER 2 Arrays Ms. Manal Al-Asmari.
BIT115: Introduction to Programming
Chapter VII: Arrays.
Lecture 5 D&D Chapter 6 Arrays and ArrayLists Date.
BIT115: Introduction to Programming
BIT115: Introduction to Programming
BIT115: Introduction to Programming
BIT115: Introduction to Programming
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];
Object Oriented Programming in java
BIT115: Introduction to Programming
CS2011 Introduction to Programming I Arrays (I)
Announcements Lab 7 due Wednesday Assignment 4 due Friday.
Announcements Lab 6 was due today Lab 7 assigned this Friday
Dr. Sampath Jayarathna Cal Poly Pomona
Arrays in Java.
Data Structures & Algorithms
Week 7 - Monday CS 121.
Presentation transcript:

Lecture 17 Instructor: Craig Duckett Passing & Returning Arrays

2 Assignment 3 Revision (LECTURE 16) GRADED! RETURNED! Monday, June 1 Assignment 4 (LECTURE 20) Wednesday, June 10 Assignment 4 Revision (LECTURE 21) Monday, June 15 Assignment Dates DUE ONE WEEK

Today’s Topics Arrays (Recap) Arrays as Parameters Returning an Array Assignment 4 Basic and Advanced Overview WALK-THROUGH: ICE 17.1

And now... The Quiz

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 int grade1 = 100; int grade2 = 89; int grade3 = 96; int grade4 = 100; int grade5 = 98; 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: 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 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: 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 = new int[5]; 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 }; Even though you declared an array with [5] elements, the “count” of the elements starts with [0] In memory, the array elements are mostly stored in sequential order

Recap: Arrays grades[0] = 100; grades[1] = 89; grades[2] = 96; grades[3] = 100; grades[4] = 98; The entire collection of element identifiers is called the index grades[0] = 100; grades[1] = 89; grades[2] = 96; grades[3] = 100; grades[4] = 98; Each individual element identifier in the index is called a subscript

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

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 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 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--; } Loops

Arrays as Parameters

class ArrayHelper - PrintArray method main - shortArray - longArray

Arrays as Parameters Passing an array as a parameter

Arrays as Parameters

But how does this really work in memory? How does the method actually know which array to point to and use? 1, 3, 5 NOTE! Passing an array to a method behaves differently than passing a primitive data type! The array isn’t copied to the method, the method points to the array data!

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

Arrays as Parameters 1, 3, 5 1, 2, 3, 5, 7 shortArray longArray (1) PrintArray method is called and and checks name in parameter which is a named storage space in the memory heap (2) PrintArray than takes the array element data as needed and plugs it through the arrayName placeholder into the body of the method where it can do its work on the same array! NOTE: When a primitive data type, e.g. int, is passed to a method, its value is COPIED to the new method variable. For reference data types, a new reference is created, but unlike for primitives, the data that is referenced is NOT copied to a new area of memory. Instead the new reference is set to REFER to the original area of memory storing the data. This is known as passing by reference. As such, when arrays are concerned, simply calling/using an array method can alter/change the data in the original array since they method is pointing to the same memory location as the original array.

Arrays as Parameters 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]); } } } PassArrayChangeValues.java

Lecture 18: 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 Address showArray(numbers); public static void showArray(int[] array) { for (int i = 0; i < array.length; i++) System.out.print(array[i] + " "); } Example: PassArray.javaPassArray.java

Passing and Returning Arrays In Last Wednesday’s Class we learned how you could pass an array into a method. Today 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; } The getArray method is a public static method that returns an array of doubles. See example: ReturnArray.javaReturnArray.java double is the return type return sends back a double

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 ICE_18_PrintArray.java I’m going to walk-through the building PrintArray of the PrintArray method for ICE PART 1

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

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); } } arrayName shortArray longArray count 1, 3, 5

ICE: Arrays as Parameters In-Class Exercises: Arrays as Parameters The ICE exercises will go the remainder of class. If you finish early you are either: (a)free to go home for the evening (b)meet with your team members regarding Assignment 4 (c)work on Assignment 4