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