CS 106A, Lecture 16 Arrays

Similar documents
Arrays Chris Piech CS106A, Stanford University

Arrays Chris Piech CS106A, Stanford University

AP Computer Science. Arrays. Copyright 2010 by Pearson Education

Topic 21 arrays - part 1

arrays - part 1 My methods are really methods of working and thinking; this is why they have crept in everywhere anonymously. Emmy Noether, Ph.D.

Building Java Programs

CS 106A, Lecture 5 Booleans and Control Flow

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

CS 106A, Lecture 27 Final Exam Review 1

CS 106A, Lecture 27 Final Exam Review 1

Building Java Programs Chapter 7

Arrays. Weather Problem Array Declaration Accessing Elements Arrays and for Loops Array length field Quick Array Initialization Array Traversals

Lecture 9: Arrays. Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp. Copyright (c) Pearson All rights reserved.

CS 106A, Lecture 19 ArrayLists

Memory Chris Piech CS106A, Stanford University. Piech, CS106A, Stanford University

CS 106A, Lecture 14 Events and Instance Variables

CS 106A, Lecture 14 Events and Instance Variables

CS 106A, Lecture 7 Parameters and Return

CS 106A, Lecture 23 Interactors and GCanvas

CS 106A, Lecture 9 Problem-Solving with Strings

CS 106B, Lecture 1 Introduction to C++

CS 106A, Lecture 9 Problem-Solving with Strings

CS 106A, Lecture 25 Life After CS 106A, Part 1

CS 106A, Lecture 11 Graphics

CS 106A, Lecture 24 Interactors and NameSurfer

CS 106A, Lecture 20 ArrayLists and HashMaps

Lecture 10: Arrays II

CS106A Review Session

CS 106X, Lecture 16 More Linked Lists

CS 106A, Lecture 3 Problem-solving with Karel

Topic 22 arrays - part 2. Copyright Pearson Education, 2010 Based on slides by Marty Stepp and Stuart Reges from

CS 106X, Lecture 10 Recursive Backtracking

Array basics. Readings: 7.1

CS 106A, Lecture 3 Problem-solving with Karel

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Homework Assignment 2: Java Console and Graphics

Array basics. How would you solve this? Arrays. What makes the problem hard? Array auto-initialization. Array declaration. Readings: 7.

Expressions and Control Statements

Topic 4 Expressions and variables

Functions. Arash Rafiey. September 26, 2017

CSc 110, Autumn 2016 Lecture 15: lists. Adapted from slides by Marty Stepp and Stuart Reges

CS 106X, Lecture 14 Classes and Pointers

Expressions, Statements, and Control Structures

What is an algorithm?

Design and Debug: Essen.al Concepts CS 16: Solving Problems with Computers I Lecture #8

Solution to Section #3 Portions of this handout by Eric Roberts, Mehran Sahami, Marty Stepp, Patrick Young and Jeremy Keeshin

Expressions and Control Statements

Floating-point lab deadline moved until Wednesday Today: characters, strings, scanf Characters, strings, scanf questions clicker questions

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

More on Arrays CS 16: Solving Problems with Computers I Lecture #13

Queues and Unit Testing

Admin. CS 112 Introduction to Programming. Recap: Exceptions. Summary: for loop. Recap: CaesarFile using Loop. Summary: Flow Control Statements

CS 112 Introduction to Programming

Arrays. circleracers (one racer) Object Creation and "dot syntax" Array Operation Idiom. // the x-position of the racer float x = 0;

Searching and Sorting (Savitch, Chapter 7.4)

Strings, Arrays, A1. COMP 401, Spring 2015 Lecture 4 1/20/2015

Friday Four Square! Today at 4:15PM, Outside Gates

Java's Memory Management

Practice Midterm Examination

CSE 332: Data Structures. Spring 2016 Richard Anderson Lecture 1

Programming Karel the Robot

Building Java Programs

Arrays. Here is the generic syntax for an array declaration: type[] <var_name>; Here's an example: int[] numbers;

Control Statements. if for while

Simple Arrays. Eric Roberts CS 106A February 15, 2017

CS 106X, Lecture 23 Dijkstra and A* Search

Passing Array to Methods

Programming Languages and Techniques (CIS120)

Trace call recsum(x, 3)

Topic 11 Scanner object, conditional execution

Simple Java YEAH Hours. Brahm Capoor and Vrinda Vasavada

COSC 111: Computer Programming I. Dr. Bowen Hui University of Bri>sh Columbia Okanagan

Lecture 13: Abstract Data Types / Stacks

Arrays: An array is a data structure that stores a sequence of values of the same type. The data type can be any of Java s primitive types:

Objec&ves. Packages Collec&ons Generics. Sept 28, 2016 Sprenkle - CSCI209 1

Drawing Geometrical Objects. Graphic courtesy of Eric Roberts

CS107, Lecture 3 Bits and Bytes; Bitwise Operators

CS111: PROGRAMMING LANGUAGE II

Assignment #2: Intro to Java Due: 11AM PST on Wednesday, July 12

Design and Debug: Essen.al Concepts Numerical Conversions CS 16: Solving Problems with Computers Lecture #7

MERGESORT & QUICKSORT cs2420 Introduction to Algorithms and Data Structures Spring 2015

Tutorial 11. Exercise 1: CSC111 Computer Programming I. A. Write a code snippet to define the following arrays:

YEAH 2: Simple Java! Avery Wang Jared Bitz 7/6/2018

CSE 143 Lecture 1. Arrays (review) slides created by Marty Stepp

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

61A LECTURE 1 FUNCTIONS, VALUES. Steven Tang and Eric Tzeng June 24, 2013

Primitives, Objects, and Heap/Stack Review 1 Chris Piech CS106A, Stanford University

COE318 Lecture Notes Week 4 (Sept 26, 2011)

CS 106X Lecture 26: Inheritance and Polymorphism in C++

Practice Midterm #2. Midterm Time: Monday, July 18 th, 7pm 9pm Midterm Location: Hewlett 200

Assignment #1: /Survey and Karel the Robot Karel problems due: 1:30pm on Friday, October 7th

Section Handout #3: Strings and Files

Mehran Sahami Handout #7 CS 106A September 24, 2014

CPS 216, Problem Solving and Programming Techniques in C++ Saleh M. Alnaeli, Ph.D. Spring, Lab_Week2

CS 302: Introduction to Programming in Java. Lecture 9

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

CS 106X, Lecture 7 Introduction to Recursion

Example: Computing prime numbers

CS107, Lecture 9 C Generics Function Pointers

Admin. CS 112 Introduction to Programming. Recap: Arrays. Arrays class. Array Return (call) Array Return (declare) q Exam 1 Max: 50 Avg/median: 32

Transcription:

CS 106A, Lecture 16 Arrays suggested reading: Java Ch. 11.1-11.5 This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons Attribution 2.5 License. All rights reserved. Based on slides created by Keith Schwarz, Mehran Sahami, Eric Roberts, Stuart Reges, and others.

Where Are We in CS 106A? Karel the Robot Java Console Programs Text Processing Graphics Programs Data Structures Defining our own Variable Types GUIs 2

HW5: ImageShop You are here Arrays Midterm! The River of Java 2D Arrays Practice 3

Plan for Today Data Structures Arrays Arrays as Parameters and Return Values Announcements Practice: Swapping Elements Practice: WeatherStation Recap 4

Plan for Today Data Structures Arrays Arrays as Parameters and Return Values Announcements Practice: Swapping Elements Practice: WeatherStation Recap 5

What are Data Structures? Data structures are variable types that can store data in useful ways. 6

Why Are Data Structures Useful? Consider a program similar to Weather from HW2 that prompts for daily temperatures and prints averages, high/lows, etc. Why is this hard to write with what we've learned so far? How many days' temperatures? 7 Day 1's high temp: 45 Day 2's high temp: 44 Day 3's high temp: 39 Day 4's high temp: 48 Day 5's high temp: 37 Day 6's high temp: 46 Day 7's high temp: 53 All temperatures: [45, 44, 39, 48, 37, 46, 53] Average temp = 44.6 4 days were above average. Two coldest days: 37, 39 Two hottest days: 53, 48 7

Plan for Today Data Structures Arrays Arrays as Parameters and Return Values Announcements Practice: Swapping Elements Practice: WeatherStation Recap 8

Arrays A new variable type that is an object that represents an ordered, homogeneous list of data. Arrays have many elements that you can access using indices index 0 1 2 3 4 5 6 7 8 9 value 12 49-2 26 5 17-6 84 72 3 length = 10 element 0 element 4 element 9 9

Creating an Array type[] name = new type[length]; int[] numbers = new int[5]; index 0 1 2 3 4 value 0 0 0 0 0 Java automa*cally ini*alizes elements to 0. 10

Accessing Data In An Array name[index] // get element at index Like Strings, indices go from 0 to the array's length - 1. for (int i = 0; i < 7; i++) { println(numbers[i]); } println(numbers[9]); // exception println(numbers[-1]); // exception index 0 1 2 3 4 5 6 value 0 1 2 3 4 5 6 11

Putting Data In An Array name[index] = value; // set element at index Like Strings, indices go from 0 to the array's length - 1. int[] numbers = new int[7]; for (int i = 0; i < 7; i++) { numbers[i] = i; } numbers[8] = 2; // exception numbers[-1] = 5; // exception index 0 1 2 3 4 5 6 value 0 1 2 3 4 5 6 12

Practice arrayelements1 Q: What are the contents of numbers after executing this code? int[] numbers = new int[8]; numbers[1] = 3; numbers[4] = 7; numbers[6] = 5; int x = numbers[1]; numbers[x] = 2; numbers[numbers[4]] = 9; // 0 1 2 3 4 5 6 7 A. {0, 3, 0, 2, 7, 0, 5, 9} B. {0, 3, 0, 0, 7, 0, 5, 0} C. {3, 3, 5, 2, 7, 4, 5, 0} D. {0, 3, 0, 2, 7, 6, 4, 4} 13

Arrays Of Other Types You can create arrays of any variable type. For example: double[] results = new double[5]; String[] names = new String[3]; boolean[] switches = new boolean[4]; GRect[] rects = new GRect[5]; Java ini:alizes each element of a new array to its default value, which is 0 for int and double, \0 for char, false for boolean, and null for objects. 14

Array Length Similar to a String, you can get the length of an array by saying myarray.length Note that there are no parentheses at the end! Practice: What is the index of the last element of an array in terms of its length? What is the index of the middle element of an array in terms of its length? 15

Arrays + For Loops = Just like with Strings, we can use an array s length, along with its indices, to perform cool operations. 16

Arrays + For Loops = Just like with Strings, we can use an array s length, along with its indices, to perform cool operations. For instance, we can efficiently initialize arrays. int[] numbers = new int[8]; for (int i = 0; i < numbers.length; i++) { numbers[i] = 2 * i; } index 0 1 2 3 4 5 6 7 value 0 2 4 6 8 10 12 14 17

Arrays + For Loops = Just like with Strings, we can use an array s length, along with its indices, to perform cool operations. For instance, we can read in numbers from the user: int length = readint("# of numbers? "); int[] numbers = new int[length]; for (int i = 0; i < numbers.length; i++) { numbers[i] = readint("elem " + i + ": "); } 18

Arrays + For Loops = Just like with Strings, we can use an array s length, along with its indices, to perform cool opera:ons. For instance, we can sum up all of an array s elements. int sum = 0; for (int i = 0; i < numbers.length; i++) { sum += numbers[i]; } println(sum); 19

Brief Aside: Creating Arrays Some%mes, we want to hardcode the elements of an array. int numbers = new int[7]; numbers[0] = 5; numbers[1] = 32; numbers[3] = 12;... // This is tedious! 20

Brief Aside: Creating Arrays Some%mes, we want to hardcode the elements of an array. Luckily, Java has a special syntax for ini%alizing arrays to hardcoded numbers. type[] name = { elements }; // Java infers the array length int[] numbers = {5, 32, 12, 2, 1, -1, 9}; 21

Limitations of Arrays An array s length is fixed. You cannot resize an existing array: int[] a = new int[4]; a.length = 10; // error You cannot compare arrays contents with == or equals: int[] a1 = {42, -7, 1, 15}; int[] a2 = {42, -7, 1, 15}; if (a1 == a2) {... } if (a1.equals(a2)) {... } // false! // false! An array does not know how to print itself: println(a1); // [I@98f8c4] 22

Arrays Methods To The Rescue! The class Arrays in package java.util has useful methods for manipula6ng arrays: Method name Arrays.binarySearch(array, value) Arrays.copyOf(array, length) Arrays.equals(array1, array2) Arrays.fill(array, value); Arrays.sort(array); Arrays.toString(array) Description returns the index of the given value in a sorted array (or < 0 if not found) returns a new copy of array of given length returns true if the two arrays contain same elements in the same order sets every element to the given value arranges the elements into sorted order returns a string representing the array, such as "[10, 30, -25, 17]" 23

Example: Arrays.toString Arrays.toString accepts an array as a parameter and returns a string representa0on of its elements. int[] e = {0, 2, 4, 6, 8}; e[1] = e[3] + e[4]; println("e is " + Arrays.toString(e)); Output: e is [0, 14, 4, 6, 8] 24

Plan for Today Data Structures Arrays Arrays as Parameters and Return Values Announcements Prac6ce: Swapping Elements Prac6ce: WeatherSta6on Recap 25

Passing Arrays Between Methods Arrays are just another variable type, so methods can take arrays as parameters and return an array. private int sumarray(int[] numbers) {... } private int[] makespecialarray(...) { } int[] myarray =... return myarray; 26

Passing Arrays Between Methods Arrays are just another variable type, so methods can take arrays as parameters and return an array. However, arrays are objects, so per A Variable Origin Story, an array variable box actually stores its location. This means changes to an array passed as a parameter affect the original array! 27

Arrays: Pass By Reference public void run() { int[] numbers = new int[7]; } fillarray(numbers); // modifies numbers println(arrays.tostring(numbers)); private void fillarray(int[] arr) { for (int i = 0; i < arr.length; i++) { } } arr[i] = 2 * i; 28

Plan for Today Data Structures Arrays Arrays as Parameters and Return Values Announcements Practice: Swapping Elements Practice: WeatherStation Recap 29

Announcements Assignment 4 due next Monday Graded midterms returned next week Thursday OH shi;ed to Monday this week OH back to every day star?ng next week Honor Code reminder 30

Plan for Today Data Structures Arrays Arrays as Parameters and Return Values Announcements Prac6ce: Swapping Elements Prac6ce: WeatherSta6on Recap 31

Practice: Swapping Elements Let s write a method called swapelements that swaps two elements of an array. How can we do this? What parameters should it take (if any)? What should it return (if anything)? private??? swapelements(???) {... } 32

Swap: Take 1 public void run() { } int[] array = new int[5];... swapelements(array[0], array[1]);... private void swapelements(int x, int y) { int temp = x; x = y; y = temp; } 33

Swap: Take 1 public void run() { } int[] array = new int[5];... Ints are primi,ves, so they are passed by value! Their variable boxes store their actual values. So swapelements(array[0], array[1]); changes to the parameter do not affect the... original. private void swapelements(int x, int y) { int temp = x; x = y; y = temp; } 34

Swap: Take 2 public void run() { int[] array = new int[5];... swapelements(array, 0, 1); }... private void swapelements(int[] arr, int pos1, int pos2) { } int temp = arr[pos1]; arr[pos1] = arr[pos2]; arr[pos2] = temp; 35

Swap: Take 2 public void run() { int[] array = new int[5];... swapelements(array, 0, 1); } Arrays are objects, so they are passed by reference! Their variable boxes store their... loca%on. So changes to the parameter do affect the original. private void swapelements(int[] arr, int pos1, int pos2) { } int temp = arr[pos1]; arr[pos1] = arr[pos2]; arr[pos2] = temp; 36

Plan for Today Data Structures Arrays Arrays as Parameters and Return Values Announcements Prac6ce: Swapping Elements Prac6ce: WeatherSta6on Recap 37

WeatherStation Weather Write a WeatherStation program that prompts the user to enter daily temperatures, and uses an array to produce this output: How many days' temperatures? 7 Day 1's high temp: 45 Day 2's high temp: 44 Day 3's high temp: 39 Day 4's high temp: 48 Day 5's high temp: 37 Day 6's high temp: 46 Day 7's high temp: 53 All temperatures: [45, 44, 39, 48, 37, 46, 53] Average temp = 44.6 4 days were above average. Two coldest days: 37, 39 Two hottest days: 53, 48 38

Plan for Today Data Structures Arrays Arrays as Parameters and Return Values Announcements Prac6ce: Swapping Elements Prac6ce: WeatherSta6on Recap 39

Recap: Arrays An array is an ordered, homogeneous list of data. Arrays can store both primi9ves and objects An array s length cannot be changed once it is created. There are no methods you can call on an array; however, there is the helpful Arrays class, with methods such as Arrays.toString. 40

Recap Data Structures Arrays Arrays as Parameters and Return Values Announcements Prac6ce: Swapping Elements Prac6ce: WeatherSta6on Next &me: 2D Arrays 41

Extra Slides This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons Attribution 2.5 License. All rights reserved. Based on slides created by Keith Schwarz, Mehran Sahami, Eric Roberts, Stuart Reges, and others.

Array reverse exercise Write a reverse method that reverses the elements of an array. Example: int[] numbers = {11, 42, -5, 27, 0, 89}; reverse(numbers); A:er the call, it should store: [89, 0, 27, -5, 42, 11] The code should work for an array of any size. 43

Algorithm idea Swap pairs of elements from the edges; work inwards: index 0 1 2 3 4 5 value 11 89 42 0 27-5 27-5 42 0 89 11 44

Possible algorithm Q: What is the effect of the code below? Does it reverse the array? int[] numbers = {11, 42, -5, 27, 0, 89}; // reverse the array for (int i = 0; i < numbers.length; i++) { int temp = numbers[i]; numbers[i] = numbers[numbers.length - 1 - i]; numbers[numbers.length - 1 - i] = temp; } A. Code is correct and reverses the array properly. B. Elements are reversed, but some are lost/missing. C. Indexes are off-by-1. D. Array contents are the same at the end; the code does nothing. E. None of the above 45

Correct algorithm Corrected version: int[] numbers = {11, 42, -5, 27, 0, 89}; // reverse the array for (int i = 0; i < numbers.length / 2; i++) { int temp = numbers[i]; numbers[i] = numbers[numbers.length - 1 - i]; numbers[numbers.length - 1 - i] = temp; } index 0 1 2 3 4 5 value 11 89 42 0 27-5 27-5 42 0 89 11 46