Midterms Save the Dates!

Similar documents
Midterms Save the Dates!

News. Recap: While Loop Example. Reading. Recap: Do Loop Example. Recap: For Loop Example

Intro. Iterators. 1. Access

Agenda & Reading. Simple If. Decision-Making Statements. COMPSCI 280 S1C Applications Programming. Programming Fundamentals

CMPS 10 Introduction to Computer Science Lecture Notes

Brave New World Pseudocode Reference

Using Classes and Objects. Lecture 7. Midterms Save the Dates! Extra Credit Survey

Assembler. Building a Modern Computer From First Principles.

For instance, ; the five basic number-sets are increasingly more n A B & B A A = B (1)

Survey #2. Teen Talk Barbie TM Reloaded. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu Partially Filled Arrays ArrayLists

Midterms Save the Dates!

Midterms Save the Dates!

Complex Numbers. Now we also saw that if a and b were both positive then ab = a b. For a second let s forget that restriction and do the following.

Pass by Reference vs. Pass by Value

Outline. CIS 110: Intro to Computer Programming. What Do Our Programs Look Like? The Scanner Object. CIS 110 (11fa) - University of Pennsylvania 1

Harvard University CS 101 Fall 2005, Shimon Schocken. Assembler. Elements of Computing Systems 1 Assembler (Ch. 6)

Midterms Save the Dates!

Survey #2. Variable Scope. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings. Scope Static.

Programming Assignment Six. Semester Calendar. 1D Excel Worksheet Arrays. Review VBA Arrays from Excel. Programming Assignment Six May 2, 2017

Sorting Review. Sorting. Comparison Sorting. CSE 680 Prof. Roger Crawfis. Assumptions

Midterms Save the Dates!

Survey #2. Programming Assignment 3. Final Exam. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu.

Virtual Memory. Background. No. 10. Virtual Memory: concept. Logical Memory Space (review) Demand Paging(1) Virtual Memory

Final Exam. Programming Assignment 3. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Midterms Save the Dates!

Midterms Save the Dates!

Loop Transformations, Dependences, and Parallelization

PeerWise Study. Midterms Save the Dates! University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Constants Using Classes and Objects

Midterms Save the Dates!

Survey #2. Assignment #3. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings. Static Interface Types.

Introduction to Programming. Lecture 13: Container data structures. Container data structures. Topics for this lecture. A basic issue with containers

CSCI 104 Sorting Algorithms. Mark Redekopp David Kempe

CS221: Algorithms and Data Structures. Priority Queues and Heaps. Alan J. Hu (Borrowing slides from Steve Wolfman)

Today s Outline. Sorting: The Big Picture. Why Sort? Selection Sort: Idea. Insertion Sort: Idea. Sorting Chapter 7 in Weiss.

Midterms Save the Dates!

CE 221 Data Structures and Algorithms

9. BASIC programming: Control and Repetition

Assembler. Shimon Schocken. Spring Elements of Computing Systems 1 Assembler (Ch. 6) Compiler. abstract interface.

Course Introduction. Algorithm 8/31/2017. COSC 320 Advanced Data Structures and Algorithms. COSC 320 Advanced Data Structures and Algorithms

Programming in Fortran 90 : 2017/2018

Midterms Save the Dates!

Last Week: Organizing Data. Last Week: Parallel Arrays. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu.

Outline. CIS 110: Introduction to Computer Programming. Review: Interactive Sum. More Cumulative Algorithms. Interactive Sum Trace (2)

Sequential search. Building Java Programs Chapter 13. Sequential search. Sequential search

Lecture 15: Memory Hierarchy Optimizations. I. Caches: A Quick Review II. Iteration Space & Loop Transformations III.

Overview. CSC 2400: Computer Systems. Pointers in C. Pointers - Variables that hold memory addresses - Using pointers to do call-by-reference in C

Midterms Save the Dates!

Compiler Design. Spring Register Allocation. Sample Exercises and Solutions. Prof. Pedro C. Diniz

Oracle Database: SQL and PL/SQL Fundamentals Certification Course

Mathematics 256 a course in differential equations for engineering students

Problem Set 3 Solutions

Outline. Midterm Review. Declaring Variables. Main Variable Data Types. Symbolic Constants. Arithmetic Operators. Midterm Review March 24, 2014

Loop Transformations for Parallelism & Locality. Review. Scalar Expansion. Scalar Expansion: Motivation

Notes on Organizing Java Code: Packages, Visibility, and Scope

CS1100 Introduction to Programming

MATHEMATICS FORM ONE SCHEME OF WORK 2004

A Taste of Java and Object-Oriented Programming

CSE 113 A. Announcements - Lab

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Final Exam. Programming Assignment 3. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

AMath 483/583 Lecture 21 May 13, Notes: Notes: Jacobi iteration. Notes: Jacobi with OpenMP coarse grain

Esc101 Lecture 1 st April, 2008 Generating Permutation

Exercises (Part 4) Introduction to R UCLA/CCPR. John Fox, February 2005

Improving Low Density Parity Check Codes Over the Erasure Channel. The Nelder Mead Downhill Simplex Method. Scott Stransky

Lecture 5: Multilayer Perceptrons

SI485i : NLP. Set 5 Using Naïve Bayes

CS 534: Computer Vision Model Fitting

Setup and Use. Version 3.7 2/1/2014

Setup and Use. For events not using AuctionMaestro Pro. Version /7/2013

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Assignment # 2. Farrukh Jabeen Algorithms 510 Assignment #2 Due Date: June 15, 2009.

Parallelism for Nested Loops with Non-uniform and Flow Dependences

CSE 326: Data Structures Quicksort Comparison Sorting Bound

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

CS121/IS223. Object Reference Variables. Dr Olly Gotel

Survey #2. Programming Assignment 3. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Parallel Numerics. 1 Preconditioning & Iterative Solvers (From 2016)

Why visualisation? IRDS: Visualization. Univariate data. Visualisations that we won t be interested in. Graphics provide little additional information

Computer models of motion: Iterative calculations

High level vs Low Level. What is a Computer Program? What does gcc do for you? Program = Instructions + Data. Basic Computer Organization

The Codesign Challenge

Some Tutorial about the Project. Computer Graphics

Nachos Project 3. Speaker: Sheng-Wei Cheng 2010/12/16

Concurrent models of computation for embedded software

Lecture 3: Computer Arithmetic: Multiplication and Division

Terminal Window. 11. Section 7 Exercises Program Memory Exercise 7-1 Swap Values in an Array Working memory Global Memory. 2 nd call 3 rd call

3D vector computer graphics

Sorting. Sorted Original. index. index

Range images. Range image registration. Examples of sampling patterns. Range images and range surfaces

such that is accepted of states in , where Finite Automata Lecture 2-1: Regular Languages be an FA. A string is the transition function,

Insertion Sort. Divide and Conquer Sorting. Divide and Conquer. Mergesort. Mergesort Example. Auxiliary Array

Cache Performance 3/28/17. Agenda. Cache Abstraction and Metrics. Direct-Mapped Cache: Placement and Access

Smart Cities SESSION II: Lecture 2: The Smart City as a Communications Mechanism: Transit Movements

Priority queues and heaps Professors Clark F. Olson and Carol Zander

Non-Split Restrained Dominating Set of an Interval Graph Using an Algorithm

An Optimal Algorithm for Prufer Codes *

5 The Primal-Dual Method

Lecture 5: Probability Distributions. Random Variables

Life Tables (Times) Summary. Sample StatFolio: lifetable times.sgp

Quicksort. Part 1: Understanding Quicksort

Transcription:

Unversty of Brtsh Columba CPSC, Intro to Computaton Alan J. Hu Thnkng About Loops Intro to Arrays (Obect References?) Readngs Ths Week: Ch 6 (Ch 7 n old 2 nd ed). Next Week: Ch 7 (Ch 8 n old 2 nd ed). (Remnder: Readngs are absolutely vtal for learnng ths stuff!) Lecture 3 Some sldes borrowed from Kurt Eselt, Tamara Munzner, and Beth Smon. Labs and Tutorals Ths week s Lab #6. Lab #7 s up on WebCT. (Any comments on TA Elan Dubrofsky, please emal me.) Mdterms Save the Dates! Mdterm # s 5:30-6:30pm on February 0 (Tuesday) n Woodward IRC 2 Done! Mdterm #2 s 6-7pm on March (Wednesday) n Woodward IRC 2 If you have an unavodable conflct for the March exam, you must emal me (wth your name, student ID, and descrpton of the tme conflct) by Wednesday, March 4! Programmng Assgnment 2 Assgnment 2 s up on WebCT! Clck on the Assgnments con. Due at NOON, March 0 (Tuesday), va electronc hand n. Start early! (I really mean t!) There s some Eclpse setup. Learnng Goals By the end of the next several lectures you wll be able to Wrte programs that make decsons ( condtonals, aka f statements) and repeat computatons ( teraton, whle loops, for loops)

Learnng Goals By the end of class today you wll be able to Thnk about and explan loops wth more sophstcaton. Reason about why a loop wll termnate, and why t wll termnate wth the rght answer. Explan what an array s and why they are useful. Wrte smple programs that declare and use arrays. (Descrbe what an obect or array reference s and why Java varables store references nstead of the array or obect tself.) Revew: whle Statement whle ( boolean expresson ) body Control flow Is boolean expresson true? If not, ext loop. Execute body of floop. Check agan, s boolean expresson stll true? If not, ext loop. Execute body of loop. and so on Repetton contnues untl expresson false. Then processng contnues wth next statement after loop Revew: for Statement publc class ForDemo for (nt counter = ; counter <= 3; counter = counter + ) System.out.prntln("The square of " + counter + " s " + (counter * counter)); System.out.prntln("End of demonstraton"); Revew: for Statement publc class ForDemo for (nt counter = ; counter <= 3; counter = counter + ) System.out.prntln("The square of " + counter + " s " + (counter * counter)); System.out.prntln("End of demonstraton"); Header has three parts separated by semcolons Intalzaton: frst part executed only one tme, at begnnng Revew: for Statement publc class ForDemo for (nt counter = ; counter <= 3; counter = counter + ) System.out.prntln("The square of " + counter + " s " + (counter * counter)); System.out.prntln("End of demonstraton"); boolean expresson: second part evaluated ust before loop body, lke n whle Revew: for Statement publc class ForDemo for (nt counter = ; counter <= 3; counter = counter + ) System.out.prntln("The square of " + counter + " s " + (counter * counter)); System.out.prntln("End of demonstraton"); Increment: thrd part executed at end of loop body Despte name, arbtrary calculaton allowed could decrement, for example! 2

Revew: Nested Loops _ 3

_ 2 _ 2 2 2_ 3 2_ Understandng vs. Tracng Tracng loop executon s not how good programmers thnk! It s an mportant skll as a fall-back, though. Understandng vs. Spellng Out Tracng loop executon s not how good good programmers thnk! It s an mportant skll as a fall-back, though. It s lke readng: Most words, you don t have to thnk about at all, e.g.: dog, cat, thnk, computer If you ht an unfamlar word, you fall-back to soundng t out, e.g.: antepenultmate Fluent readers don t even thnk about each word! (Dd you notce the double word above?) 4

Understandng a Loop So how do you try to understand a loop? Look at the loop header: What varable(s) control the loop? How s t makng progress toward termnaton? Look at the loop body: What gets accomplshed each tme you go through the loop? Can you summarze what the entre loop does? Understandng a Loop Let s look at the prevous example Understandng a Loop OK goes from to 3, so I do somethng 3 tmes goes from to 3 Understandng a Loop Understandng a Loop goes from to 3 aha, so I prnt 3 numbers n a row, * Understandng a Loop and then I prnt the newlne 5

Understandng a Loop so ths whole loop body prnts a row of tmes to 3 Understandng a Loop so ths whole thng prnts a 3x3 multplcaton table Last tme, we wrote a loop to compute the balance n a loan after a certan number of payments: E.g., If I have a $00,000 loan at 5% annual nterest, and I make an annual payment of $6000, how much wll I owe after 5 years? for (nt year = 0; year < term; year++) OK, year goes from 0 to term- for (nt year = 0; year < term; year++) each tme through the loop body computes the effect of one year for (nt year = 0; year < term; year++) 6

so at the start (or end, after year++) of each loop, for (nt year = 0; year < term; year++) myloan.getbalance() wll return the correct balance after year years for (nt year = 0; year < term; year++) When the loop ends, year wll be exactly equal to term for (nt year = 0; year < term; year++) So, when the whole loop ends, myloan.getbalance() wll have the answer. for (nt year = 0; year < term; year++) OK, year goes from 0 to term- (when year==term, the loop exts) Ths s a termnaton argument. Always know why your loop should termnate! At the start (or end, after year++) of each loop, myloan.getbalance() wll return the correct balance after year years Ths s a loop nvarant. Helpful and powerful way to thnk about loops. Great to put n a comment! Loan Amortzaton: Computng Payment How do we compute the rght payment amount to pay off a loan after some number of years? E.g., What s my annual mortgage payment f I borrow $,900,000 at 5.85%, amortzed over 25 years? What s my monthly car payment f I borrow $40,000 for 60 months at 0.3% per month? (Yes, there exsts a formula for ths, but what we re dong s a general way to solve problems, even when there sn t a formula for t.) 7

Loan Amortzaton How do we compute the rght payment amount to pay off a loan after some number of years? Have two guesses: toolow and toohgh Try a guess halfway n between. Compute the loan balance usng guess. If guess was too hgh, then toohgh = guess else toolow = guess. Repeat Loan Amortzaton How do we know that our program wll termnate? How do we know that our program wll compute the correct result? Loan Amortzaton How do we know that our program wll termnate? Inner Loop: years starts at 0 and counts up to term. Wll always execute exactly term tmes. Outer Loop: The gap between toolow and toohgh gets cut n half each teraton. These are termnaton arguments (aka rankng functons). You should always know why your loops wll termnate. Loan Amortzaton How do we know that our program wll compute the correct result? Inner Loop: At each teraton, balance s always the correct value after years years. Outer Loop: At each teraton, toolow s always less than or equal to the correct value, and toohgh s always greater than or equal to the correct value. These are the loop nvarants. Questons? Representng Lots of Data Consder the UBC student regstraton system: must store nfo for all students the system lkely uses a class called Student How do we store all the students? Student t student0 t0 = new Student(); t() Student student = new Student(); // 34,997 lnes of code omtted!!! Student student34999 = new Student(); Yuck! There must be a better way! 8

Arrays Arrays let you create a bunch of varables (all of the same type), that you refer to by array name and number (called the ndex). Example: nt[]x= new nt[0]; gves you 0 nt varables named x[0], x[], x[2],, x[9] nstead of nt x0, x, x2, x3, x4, x5, x6, x7, x8, x9; nt[ ] x = new nt[0]; nt[ ] x = new nt[0]; Type of the varable nt[ ] x = new nt[0]; The varable name. In both cases, these are reference varables. (More on reference varables later ) nt[ ] x = new nt[0]; The keyword new to allocate memory nt[ ] x = new nt[0]; The constructor for the obect or array 9

nt[ ] x = new nt[0]; nt[ ] x = new nt[0]; s Scanner Obect x array of 0 nt varables Syntax: type[] varablename = new type[sze]; Examples: double[] dataset = new double[30]; nt[] quzscores = new nt[5]; Strng[] args; Usng Arrays Syntax: varablename[ndex-expresson] If var s an array (reference) varable of type type[], then var[expr] s a varable of type type. Examples: double[] dataset = new double[30]; dataset[0] = dataset[]/2; Usng Arrays nt[ ] x = new nt[0]; Usng Arrays nt[] x = new nt[0]; x[0] = 3; x[0] x[9] x array of 0 nt varables x 3 array of 0 nt varables 0

Usng Arrays nt[] x = new nt[0]; x[0] = 3; x[] = ; Usng Arrays nt[] x = new nt[0]; x[0] = 3; x[] = ; x[9] = x[0]+x[]; x 3 array of 0 nt varables x 3 4 array of 0 nt varables Array Intalzers Array Length You can ntalze an array when t s declared: nt[] x = 3,,4; Strng[] colours = red, green ; Syntax: varablename.length If var s an array (reference) varable, then var.length s an nt contanng number of entres t n array. Examples: double[] dataset = new double[30]; dataset.length == 30 Note that ndces go 0.. dataset.length-! Array Length Syntax: varablename.length No parentheses Not a method call If var s an array (reference) varable, then var.length s an nt contanng number of entres t n array. Examples: double[] dataset = new double[30]; dataset.length == 30 Note that ndces go 0.. dataset.length-! Loops and Arrays Loops and arrays go together perfectly: Loops repeat some statements a whole bunch of tmes, but only type them once. Arrays create a whole bunch of varables (of the same type), wth only one declaraton. Example: Addng up elements n an array: nt total = 0; for (nt =0; < x.length; ++) total += x[];

Teen Talk Barbe In 993, Mattel ntroduced Teen Talk Barbe, a doll programmed to speak random phrases. Each doll had a random selecton of 4 phrases from a lst that ncluded: You can never have enough clothes. Let s go shoppng! Math class s tough. (The Talkng GI Joe doll sad Vengeance s mne! and Dead men tell no les. ) Customzable Talkng Doll Imagne a customzable doll nstead. When frst turned on, parents put n fve phrases. After that, each tme doll actvated, t randomly says one of the phrases. How would you program ths? For smplcty, let s ust use strngs. Questons? Workng wth Obects (Real World) Have you shopped at Ikea? How do you buy some Vardag candles? An Ektorp sofa? Have you flown on a commercal arlner? How do brng a wallet or a purse? How about 20kg sutcase? Have you sked/boarded at a bg resort? What do you do wth your lp balm or toque when you re not usng t? How about a cooler full of beverages? Workng wth Obects (Real World) General prncple: For thngs that are small and convenent, carry the thng tself. For thngs that are bg and unweldy, carry some sort of tag (or reference or ponter or address) for the thng. The thng sts n some storage area desgned for bg, unweldy thngs. Java does the same thng! Recap: Prmtve Types vs. Classes Prmtve Types Pre-defned n Java Smplest thngs, e.g., nt Operators: +, -, Values belong to types. E.g., 3 s an nt, 3.459 s a double Lterals Classes Wrtten by other programmers or by you Can be arbtrarly complex Methods Obects belong to classes E.g., you are a UBC Student Constructors 2

Prmtve Types: Varables Hold Values Java prmtve types are small and smple. Java varables hold values for prmtve types. Classes: Varables Hold References Classes can be arbtrarly bg and complex Java varables hold obect references for classes. answer 42 avogadrosnumber 6.02E23 myrect mysalary Rectangle x=5 y=0 heght=20 wdth=30 BgInteger 000000000000 Obect References Remember ths dstncton. For prmtve types, varables hold the value. For classes, varables hold reference to obect Declaraton creates varable that can hold a prmtve value or an obect reference. Constructor creates the obect tself. BgInteger mysalary = new BgInteger( 000000000 ); Why Care About References? You go skng wth a frend. You splt a granola bar wth hm. He eats hs half. Does t affect yours? You make a party mx CD for a frend. Her dog chews t up. Does that affect your CDs? Why Care About References? You go skng wth a frend. You have the hotel make a copy of your hotel key for your frend, so he can leave some stuff there. He trashes the room. Does t affect your room? Your parents get an extra credt card for you, on ther account. You go wld on a shoppng spree. Does ths affect your parents credt? Why Care About References? Sometmes t can matter. Just lke n real lfe, t can matter f: There are more than one reference to the obect. (Ths s called alasng.) The obect can be changed. (Ths s called beng mutable.) More on these concepts later! 3