Chapter 12: Arrays Think Java: How to Think Like a Computer Scientist by Allen B. Downey

Similar documents
Chapter 4: Conditionals and Recursion

LAB 7. Objectives: Navin Sridhar D 8 54

LAB 13: ARRAYS (ONE DIMINSION)

1 Short Answer (10 Points Each)

Chapter 13: Arrays of Objects

Array. Lecture 12. Based on Slides of Dr. Norazah Yusof

Methods CSC 121 Spring 2017 Howard Rosenthal

Chapter 6 Arrays. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Methods CSC 121 Fall 2016 Howard Rosenthal

Assignment 2.4: Loops

Chapter 11: Create Your Own Objects

Last Class. While loops Infinite loops Loop counters Iterations

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Chapter 5 Lab Methods

4. Java language basics: Function. Minhaeng Lee

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

BlueJ Demo. Topic 1: Basic Java. 1. Sequencing. Features of Structured Programming Languages

Chapter 5 Lab Methods

Chapter 8 Multi-Dimensional Arrays

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

Chapter 6 Single-Dimensional Arrays. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.

8/2/10. Looking for something COMP 10 EXPLORING COMPUTER SCIENCE. Where is the book Modern Interiors? Lecture 7 Searching and Sorting TODAY'S OUTLINE

Arrays and Strings. Arash Rafiey. September 12, 2017

Basic Computation. Chapter 2

Intro to Programming in Java Practice Midterm

Fundamentals of Programming Data Types & Methods

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

CSE 1223: Exam II Autumn 2016

A+ Computer Science -

Arrays. Eng. Mohammed Abdualal

Choose 3 of the 1 st 4 questions (#'s 1 through 4) to complete. Each question is worth 12 points.

Course Outline. Introduction to java

Chapter 5 Lab Methods

BASIC INPUT/OUTPUT. Fundamentals of Computer Science

Array basics. Readings: 7.1

Robots. Byron Weber Becker. chapter 6

Java Coding 3. Over & over again!

BİLGE KÖROĞLU. Lecture Notes (May 2 4, 2007) METHOD DECOMPOSITION and ARRAYS

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

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Chapter 7: Arrays CS 121. April 9, Department of Computer Science College of Engineering Boise State University. Chapter 7: Arrays CS / 41

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal

Types in Java. 8 Primitive Types. What if we want to store lots of items e.g. midsem marks?

Computer Science is...

Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal

Over and Over Again GEEN163

Programming with Java

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency

CS1150 Principles of Computer Science Arrays

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently.

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

COMP String and Console I/O. Yi Hong May 18, 2015

Subject: Computer Science

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

STUDENT LESSON A12 Iterations

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

COMP Computer Basics. Yi Hong May 13, 2015

Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal

LECTURE 17. Array Searching and Sorting

2. What are the two main components to the CPU and what do each of them do? 3. What is the difference between a compiler and an interpreter?

Chapter 7 Single-Dimensional Arrays

ITI1120 Introduction to Computing I Exercise Workbook Fall 2012

Java Programming. Computer Science 112

Ch. 6. User-Defined Methods

Chapter 7: Arrays and the ArrayList Class

3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal

Flow of Control. Chapter 3

8.14 Exercises 101. // if n is even, the result is t squared // if n is odd, the result is t squared times x

5/31/2006. Last Time. Announcements. Today. Variable Scope. Variable Lifetime. Variable Scope - Cont. The File class. Assn 3 due this evening.

Input. Scanner keyboard = new Scanner(System.in); String name;

Chapter 1 Lab Algorithms, Errors, and Testing

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

Chapter 6: Arrays. Presentation slides for. Java Software Solutions. for AP* Computer Science 3rd Edition

Functions. Arash Rafiey. September 26, 2017

Passing Array to Methods

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

It is a constructor and is called using the new statement, for example, MyStuff m = new MyStuff();

11/19/2014. Arrays. Chapter 6: Arrays. Arrays. Arrays. Java Software Solutions for AP* Computer Science A 2nd Edition

Pace University. Fundamental Concepts of CS121 1

Lecture 17. Instructor: Craig Duckett. Passing & Returning Arrays

Lecture #8-10 Arrays

Chapter 4 Lab. Loops and Files. Objectives. Introduction

&KDSWHU$UUD\VDQG9HFWRUV

Formatting Output & Enumerated Types & Wrapper Classes

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Flow of Control. Chapter 3

Arrays. CS Feb 2008

A+ Computer Science -

Introduction. two of the most fundamental concepts in computer science are, given an array of values:

while (/* array size less than 1*/){ System.out.print("Number of students is invalid. Enter" + "number of students: "); /* read array size again */

CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING

CS 170 Exam 2. Version: A Fall Name (as in OPUS) (print): Instructions:

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

St. Edmund Preparatory High School Brooklyn, NY

New Concepts. Lab 7 Using Arrays, an Introduction

COMP-202: Foundations of Programming. Lecture 5: Arrays, Reference Type, and Methods Sandeep Manjanna, Summer 2015

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

Introduction to Software Development (ISD) David Weston and Igor Razgon

Transcription:

Chapter 12: Arrays Think Java: How to Think Like a Computer Scientist 5.1.2 by Allen B. Downey

Current Options for Storing Data 1) You need to store the room temperature, such as 62.5, in a variable. What would you use? a variable of type double, such as double roomtempf = 62.5; 2) You need to store all the attributes for an automobile (such as color, mileage, engine type, cost) in a variable. What would you use? an object of class Car, such as: Car auto = new Car(Color.red,42,"hybrid", 20000); you would have to define the Car class yourself 1-2

A new need, storing many of one type 3) You need to store the high temperature every day for the last year, what would you use? an array of double, such as double [] dailyhigh = new double[365]; 4) You need to store the inventory of all 1200 cars you're trying to sell, what would you use? an array of class Car, such as: Car [] inventory = new Car[1200]; 1-3

Review: Two Ways of Representing Information in Java Primitive types a single quantity int x = 6; x 6 Object types a single entity with multiple attributes Point center= new Point(1,8); 1-4

Arrays: a third way of representing information An array is a set of values where each value is identified by an index. array elements int size = 6; array index 1-5

Access Array Elements using the [ ] operator Note: as with String, elements go from 0 to 3 count[4] = 2; ArrayOutOfBounds Execption What does this do? count[ count[2] ] = 5; 1-6

Using a Loop (Traversal) to print all the items Standard while loop i goes from 0 to 3 When i gets to 4, loop condition fails, exit count[4] is not accessed 1-7

For Loops Has same components as while loop More compact, all control info in header The general syntax looks like this: Equivalent to this while loop: 1-8

Example: For vs While Loop This for loop Works the same as this while loop 1-9

Array Length All arrays have one named instance variable: length Holds the size of the array how many items it can store better to use length field as upper bound of loop last time body of loop is executed is when i = count.length 1 (position of last element) 1-10

Array Initialization When relatively few items need to be initialized, an initialization list can be used to initialize the array. int[] highs = {65, 69, 72, 78, 61 }; The numbers in the list are stored in the array in order: highs[0] is assigned 65, highs[1] is assigned 69, highs[2] is assigned 72, highs[3] is assigned 78, highs[4] is assigned 61. 8-11

Review: The Scanner Class To read input from the keyboard we can use the Scanner class. The Scanner class is defined in java.util, so we will use the following statement at the top of our programs: import java.util.scanner; To create a Scanner object: Scanner keyboard = new Scanner(System.in); 2-12

Read from keyboard with Scanner Examples read the next word (til next white space) as String String word = keyboard.next(); read to the end of the line as a String String line = keyboard.nextline(); read the next number as an int int x = keyboard.nextint(); read the next number as a double double y = keyboard.nextdouble(); 2-13

Do Lab 12 Part A (Problems 1 through 5) 1-14

Checkpoint

Checkpoint int [] employeenumbers = new int[100]; double [] payrates = new double[25]; 0 to 3 1 2 3 4 5

Checkpoint

Checkpoint result = numbers1[0]*numbers2[3]; for (int k=0; k<array.length; k++) array[k]=-1;

Copying Arrays wrong way x Creates one array of three doubles Copies reference to array from variable a to b Doesn't make a separate copy A form of aliasing Change in one array show up in the other 1-19

Side effects of Aliasing a[1] = 8.1; System.out.println( b[1] ) // prints 8.1 b[2] = 3.4; System.out.println( a[2] ) // prints 3.4 8.1 3.4 1-20

Copying Arrays Right Way 1-21

Using a For Loop to do the same For loop that uses the length of a as the size: 1-22

Arrays and Objects In many ways, arrays behave like objects: When you declare an array variable, you get a reference to an array. You have to use new to create the array itself. When you pass an array as an argument, you pass a reference, which means that the invoked method can change the contents of the array. 1-23

Difference between a Rectangle A Rectangle object and an Array of 4 int? Change first value in Rectangle box.x = 25; // fields referred to by name 1-24

Difference between a Rectangle and an Array of 4 int? An Array of 4 int elements: int [] box = {0,0,100,100}; Change first value in box array: box[0] = 25; // elements referred to by index 1-25

Another difference: Array elements must all have same type Objects of class Tile have a char and an int class Tile { } char letter; int value; An array can only hold all char data or all int data, not both, so this could not be represented using an array. 1-26

Do Lab 12 Part B (Problems 6-8) 1-27

Random Numbers Most computer programs are deterministic do the same thing each time they run usually a good thing same calculation should give the same result Some applications need to be unpredictable Games, modeling complicated systems (weather) Sources of truly random numbers: http://qrng.anu.edu.au/ 1-28

Assignment 12 The following slides are to help you visualize the goal of the code you are writing in assignment 12. 1-29

Pseudorandom Numbers We can make computers seem nondeterministic generate numbers using a math formula built into Math.random method code to print 10 pseudorandom numbers: 1-30

Math.random method 1-31

Arithmetic with Random Numbers What if you print x *10? 10 + x? (int) (x*6) + 1; 1-32

Assignment 12 problem 2 Write a method randomint(int low, int high) returns a random number between low (inclusive) and high (exclusive). Math notation: [low, high) randomint(15, 20) produces 15 19 randomly 1-33

Method to create a random array // in main: int [] arr = randomarray(8); 1-34

Method to print an array // in main: int [] arr = randomarray(8); printarray( arr ); 1-35

Counting Suppose the array arr contains test scores: 98 86 79 90 89 88 88 97 92 90 87 69 66 60 86 85 84 77 53 90 79 90 87 74 How many A's were there? How many B's? int counta = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] >= 90) counta++; } 1-36

A method that counts how many values an array has in a given range // in main int numas = inrange( arr, 90, 101); int numbs = inrange( arr, 80, 90); notice, no {} needed when only 1 statement in if statement true block 1-37

Number of Tests Histogram of Test 2 Scores int [ ] scores = {98, 86, 79, 90, 89, 88, 88, 97, 92, 90, 87, 69, 66, 60, 86, 85, 84, 77, 53, 90, 79, 90, 87, 74}; Test Score process scores array into a second array that holds the counts for each possible test score 1-38

One way to create a Histogram Make a separate variable for each count? int count0 = inrange(scores, 0, 1); int count1 = inrange(scores, 1, 2); int count2 = inrange(scores, 2, 3);... int count99 = inrange(scores, 99, 100); painful! How about an array to hold all the counts? 1-39

Better way to create a Histogram Make an array to hold all the counts! int[] counts = new int[100]; for (int i = 0; i < counts.length; i++){ counts[i] = inrange(scores, i, i+1); } Note variable i being used to index counts AND provide limits to inrange How many times do we have to traverse the scores array? 1-40

More efficiently create a Histogram Use the test score itelf as the index to counts! int[] counts = new int[100]; for (int i = 0; i < scores.length; i++){ int index = scores[i]; counts[index]++; } only makes one pass through scores array runs much faster: O(n) vs O(n 2 ) 1-41

Draw a Histogram bar chart int [] arr = { 4,2,4,2,1,2,0,3,0,0,1,2,2}; int [] counts; < make a histogram of arr > [0] XXX [1] XX [2] XXXXX [3] X [4] XX After you've processed data from arr into counts Make a for loop that repeats the number of elements in counts array print the index, then on same line, call bar on counts[index] to print row of X's 1-42

A method that prints a horizontal bar bar(5); // bar(8); // prints XXXXX prints XXXXXXXX pseudocode: method bar, takes parameter length loop that repeats length times print 1 "X" to console after loop, go to new line (println) 1-43

Sorting Arrays [Optional] Computer scientists often need to sort arrays Why? Because it s easier to find things in the array when it is sorted Most data looks better displayed in sorted form (phone books, employee records, Lacrosse games) How can we sort an array? What is the algorithm? A: There are several!! 44

Bubble Sort Bubble sort is one of the simplest sorting algorithms It proceeds through a sequence of iterations, each time moving the next largest item into its correct position On each iteration, it compares each pair of consecutive elements, moving the larger element up 45

Bubble Sort data 0 1 2 3 55 22 99 66 55 46

Bubble Sort data 0 1 2 3 55 22 99 66 if (data[k] > data[k+1]) > 55? 47

Bubble Sort data 0 1 2 3 55 22 99 66 swap(data, k, k+1); swap 48

Bubble Sort data 0 1 2 3 22 55 99 66 55 49

Bubble Sort data 0 1 2 3 22 55 99 66 > 55? 50

Bubble Sort data 0 1 2 3 22 55 99 66 99 51

Bubble Sort data 0 1 2 3 22 55 99 66 > 99? 52

Bubble Sort data 0 1 2 3 22 55 99 66 swap 53

Bubble Sort data 0 1 2 3 22 55 66 99 Notice how the data bubbles up through the array moving slowly, one bin at a time After N-1 Passes or Sweeps, the final array is guaranteed to be sorted in ascending order, no matter what input data 54

Selection Sort Another way of sorting is the selection sort The main idea is to keep finding the smallest (and next smallest) items in the array And move them into correct position (swap) 55

Selection Sort data 0 1 2 3 55 22 99 66 smallest 55 small_pos 0 k 0 55 < smallest? F 56

Selection Sort data 0 1 2 3 55 22 99 66 smallest 55 small_pos 0 k 0 22 < smallest? T 57

Selection Sort data 0 1 2 3 55 22 99 66 smallest 22 small_pos 1 k 0 22 < smallest? T 58

Selection Sort data 0 1 2 3 55 22 99 66 smallest 22 small_pos 1 k 0 99 < smallest? F 59

Selection Sort data 0 1 2 3 55 22 99 66 smallest 22 small_pos 1 k 0 66 < smallest? F 60

Selection Sort SWAP data 0 1 2 3 55 22 99 66 smallest 22 small_pos 1 k 0 swap(data, k, small_pos); 61

Selection Sort Repeat 0 1 2 3 22 55 99 66 smallest 55 small_pos 1 k 1 55 < smallest? F 62

Swapping two array elements public static void swap( int [] arr, int j, int k) { int temp = arr[j]; arr[j] = arr[k]; arr[k] = temp; } 1-63