New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here

Prog and Problem Solving I

by: Arvid Jones

Prog and Problem Solving I CSE 1301

Arvid Jones

GPA 3.72

Briana Morrison

Almost Ready


These notes were just uploaded, and will be ready to view shortly.

Purchase these notes here, or revisit this page.

Either way, we'll remind you when they're ready :)

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

Briana Morrison
Class Notes
25 ?




Popular in Course

Popular in Computer Engineering

This 80 page Class Notes was uploaded by Arvid Jones on Tuesday October 20, 2015. The Class Notes belongs to CSE 1301 at Southern Polytechnic State University taught by Briana Morrison in Fall. Since its upload, it has received 77 views. For similar materials see /class/225461/cse-1301-southern-polytechnic-state-university in Computer Engineering at Southern Polytechnic State University.

Similar to CSE 1301 at

Popular in Computer Engineering


Reviews for Prog and Problem Solving I


Report this Material


What is Karma?


Karma is the currency of StudySoup.

You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 10/20/15
5m sourNERN PDLYTECHNIE 3W snumsau PnLvTEcHNIn 5an umvERSiTv smz LinivERsiTi Objectives Lecture 80 Review static vs dynamic collections Discuss dynamic collection API Dynamic Collections Utilize a collection example Briana B Morrison Figu39esfmm Lewis cu Samar Sniuuanf AeesmWesiey 5m saurusm anscmu snurHERN PnLv rEcHMIc smz univEHsin 393 5mg univERsm Arrays Dynamic Arrays Allocate a contiguous section ofmemory 39 Arrays are 900d ifY0 know hOW large the Homo eneous collection will be 9 But ifthisisn t known beforehand how big Access Via index is enoug One approach lttypegt NAM E e Allocate for N NAME new lttypegtISIZE 7 When N i5 exceeded Aiieeate 2N and upyN intu new space Free up engmai space fur N 7 Time consuming memory allocationcopy 5m snumERN PnLv rEcHNI 3m snumERN Pnu rzcumc 51m umvERsm 51an univERsm Reallocating an Array Reallocating an Array Original Original x I When full When full SOUTHERN POLYTECHNIC STATE UNIVERSITY Reallocating an Array Original When full SOUTHERN POLYTECHNIC STATE UNIVERSITY Reallocating an Array Original W a ggu When full 1H4u m uprv v dq null W SDSU SOUTHERN POLYTE CHNIC STATE UNIVERSITY Collection APls 0 Let s not reinvent the wheel 0 Other APIs provide access to collections using System Collection Generic 0 List singlereference oneway collection 0 LinkedList doublereference twoway Queue first in first out FIFO 0 Stack first in last out FILO 0 Dictionary keyvalue pairs 0 Methods to m search iterate across these collections SOS SOUTHERN PDLYTECHNIC STATE UNIVERSITY Reallocating an Array Original W l nl r ml l When full SOUTHERN POLYTECHNIC STATE UNIVERSIT39Tr Reallocating an Array Original eeeeee When full MMJFQMM Garbage Collection IIIFliIllr wr e ll mw1 SDSU SOUTHERN POLYTECHNIC STATE UNIVERSITY Focus on ListltTgt List provides for growth dynamic Has capacity amp count Capacity size allocated Count number of slots used Reallocated automatically Grows when full to 2x Shrinks when count 12 capacity shrinks to 23 capaCIty so we don t thrash Provides pseudoimmediate access Gory details are hidden from us Sm snumERN PDLYTECHNIE 3m snumERN museum 5an IJIillVERSlT 5mg univzasm List API 1301 Asteroids in XNA ListltTgt rConstructormo hold stuffoftype T WWW 39 V Addirr Adds oblect oftype r to end of list emoveT e Deletes first occurrence of match RemoveAtint e Removes the oblect at position So nsertT int rAdds obiect at speci ed position Searching 7 CuntainsEXistsFindFindAllFindlndEXFindLast 5m saumm anscnm w snurusm PnLv rEcrml sms univsnsiw aw imimsirv A Motivating Example Asteroids Considerations Asteroids Game Collection of rocks Rocksasteroids ying around Collection of missiles hip Missiles Rock position velocit y Ship position movement shield What considerations must be made Missile position velocity Collision Detection mu snumERN pnmscumc 51sz mivERSlh Summary Arra 7 Fixed in size too smalllarge e immediate access Via index 7 Don t forget to allocate each element ifneeded List 7 Dynamicin size 7 Pseudorirnrnediate access More details ofC ListltTgt http rnsdn miciusuri cumenruslibraryEshZEle aspx m sunnian Pnu rscuuic 3m sauntan PDLYYECHNIE 51sz urtivERsm e sms univERsm Topics Lecture 2 39 Rev39ew Character Strings Variables and Assignments Data Types Primitive Data Types Briana B Morrison Figures rm Lewis cu Sabaaxe Snluuanf Aessm Weeiey W snumsm PDLVTECHNII W S uTNERN PDLYTECHNIE 5mg UHWERStl t39 5w uHivERsil V Review C program structure my Comments EggEi Z gueneeamm Identi ers mum meet White space 1 quotWm Objects temmmn m Classes Methods 50539quot 5mm mama sme univzasm W tngtmvezzwzm Program Structure Building Blocks Comments In the C programming language A program is made up of one or more classes A class contains one or more metho s A method contains program statements Comments explain the program to yourself and others Block comments 7 Can span several lines 7 Begin wtn These terms will be explored in detail n w throughoutthe course 7 Compiler ignores all text between and V Line comments An application always contains a method i 7 Startvvith called Mal n 7 Cumpilerignurestextfrurn tu end uflirie 5m snurNERN Pomscumc soumERN pnmscumn 5mg umvERsm 395 5m unwsasm Identifiers symbolic names quot quot Identi ers are used to name classes variables and methods Identi er Rules Must start with a letter Can contain essentially any number of letters and digits but Case sensitive Number7 and number7 are differentl Cannot be keywords or reserved words also gratu wgwmr mu sturivgwmm White Space Topics Spaces blank lines and tabs are called white space ReVIew White space is used to separate words and 39 Ch araCter 5m 95 symbols in a program Variables and Assignments Extra white space is ignored Primitive Data Types A valid Cit program can be formatted many ways Programs should be formatted to enhance readability using consistent indentation svsu asurrvszivmm am elumlgswmm CharacterStrings Write and WriteLlne Methods comm on menus whatever m am he a and one i Object in C de ned by string class gv J K y g y String literal is 0 or more characters Outputdevme meter enclosed with double quotes Mumtur 3de name 9 The quick brown fox jumpedquot Cunsulerclass yquot om r Dialects Can contain any valid character WritELlnE methudmcludes a newlmequot charmer 5m snurNERN PDLVTECHNIE 3W snurNERN pnmscnmn 5an unwsnsm smz UulvERsm39 string Concatenation Operator String literals cannot span lines Combines string literals with other data types 110 v v Console0utwr1teL1nE greetlng Outputis39 W V Hello there 5m snumERM anmmn 5m unwsasm 3m snurHERN pnmzcumc snrs u 1i y The Operator H 39 What it does depends on the order H String concatenation addition stnng number stxmg em a m A w n m 5mm enmecm39 W snumERN PnijrEcuNI 51sz umvzwsm t snrsumvsksm Escape Sequences newquot sequeme can ummmm 1v gunmani canutmlnmnudunnn 39 w FIGURE 11 c escane smuemes f 31 m 1 39 point t m quothumMr 930 l SDSU Sm snurNERN Pomscuuic 5an umvERsm Topics 3930 soumERN PoLvTEcuNin smz univzasirv Variables ariable is a name for a location in memory used to hold a data value VI w Character Strings A variable must be declared by specifying the Variables and Assignments variable39s name and the type of information that it will ho d Primitive Data Types an typl umbi nam ml mun ml mum mm quotsun Mum vnniu an In mum In on uuumun saumsim murmurquot 5m univEnsir i mm is mu snurusau PDLVTECHNIE snrs unwsasirv Conventions l Names ofvariables sho meaningful and re ect the data they will 5 ore mumm mi This makes the logic ofthe program clearer A Don39t skimp on characters but avoid Um W extremely long names Avoid names similarto 0 keywords snumsim PanscHNic 51m umvERsm Assignment An assignment statement changes the value of a va 39 The assignm Tl The expression on the right is evaluated and the result is stored in the variable on the left The value ha 39 Yo can only assign a value to a variable that is consistent with the variable39s declared type 3951 salinian PDLYYECNNIE sms uulvERStTv Assignment Operator Syntax ria e ent operator is the sign expression operators and operands that evaluate to a single I e value is then assigned to target in total is ovemrlnen target must be a variable or constant value must be compatible with target39s data type SM S uYNERN PDLVTECHNIE WW S UTNERN PDLVTECNNIE srArE UHlVERSlT t smz lllIlVERSt n Examples 5 1m numPlayers 1e numPlayers holds in numPlayers e numPlBVers noquot holds e Dedare a variabe ony once m 3ng 5 Once a variable is declared its data nr VDLEIABE ieeeltee type cannot be changed These statements The next statement is lllegal 111 height quot21gb 2 wenght 15 mt dE nEd nr weight 2n u2 generate a compiler error alsozihtquot5tt2itm39 SPSU iE f tte3932it39J quotquotquot a Constants 39 Value cannot chan edurin ro ram Once a variable is declared Its data executi g g p 9 type cannot be change syntax These statements mes aaeaeyae double cashI Han Bingnedv 1 Note assigning a value when the constant is generate a compller error declared is optional But a value must be assigned before the constant is used 503quot Equotiii itv e 2h f cquotquot39 305quot Equot5i iite3932h tquotc quotquot onstarlts Conventions Constants are useful for three important reasons Use all capital letters for constants and First they give meaning to otherwise unclear arate word th an underscore literal values Example FurexampleMAgtltiLOAD means murethanthe can dwhle TAX RATE m literal 25D Second they facilitate program maintenance 39 Dedare quot5 aquot 5 at the top onhe m so their values can easily be e lfa eunstant is used in multiple plaees its value need only be updated in une plaee Third the form establish that a value should Declare as a constant any data that should not change avoi ing inadvertent errors by other not change during program execution programmers SM S uYNERN PDLVTECHNIE WW S UTNERN PDLVTECNNIE 5mg umvERsm smz univzasm Topics Data Types R For all data assign a name identi er eVIew and a data type Data type tells compiler ow much memoryto allocate Format in which to store data Types of operations you will perform on data Character Strings Variables and Assignments Primitive Data Types Compiler monitors use of data Cit is a quotstrongly typedquot language saumsnu anmmn snurHERN PnLv rEcimlc 9 50 sms univsasm 393quot snrs univERsm Primitive Data Types 13 simple data types B subsets of integers 1quot quot quot M 2 subsets of oating point numbers Character a eaquot 33339 Lquot m3 III quot mmw39 31233332212212 Everything else is an object Mi slum 9mm up 11 min 12 o numcm pmth We mu snumERN Pnunscum snumsan anzcumn 51m umvERsm 395quot sms univERsiTv Why so many types Literals I Difference is in amount ofmemo All numeric values Withuuta decimal puint are considered 1n reserVed for lm arid hence the Size 0f Aii numeric values With decimal puintare eunsidered the value stored 12 1n testerade mu oat only has 7 signi cant digits in Cityhpuhtm qz lzaqm Signed numbers have both positive and byte ageInYears 19 negative values float salesTax usr 39 Uns39gned numbers are gt 0 double mtmsmte H725 double avugadru umher au22223 SW S uYNERN PDLVTECHNIE 7 39w S UTNERN PDLVTECHNIE 5an umvsnsm smz UHNERSl n39 Decimal Data Type char Data Type 128 bit storage One Unicode character 16 bits 2 bytes greater precision and smaller range than Type 1quot m M39quotquotquotquot39quot value MZX39M39quot value Other numeric tYPES char 2 character character suitable for nancial and monetary encoded as u encoded as FFFF calculations Example declarations char Elnalerade char newllne tab acuhleouccee 5m saumsau ansmm 5m uuwsasm booean Data Type Two values only false Used for decision making or as quot agquot variables Example declarations haul leampcy haul passed felled false Sm snurNERN Pomscumc 5mg umvERsm mu snumERN pnmscumn smz UNNERSl n Lecture SB More Conditionals Briana B lillon39ison Fxguesfxom Lewis cu Samar Snluuanf Ad smWesley 5m S UYHERN ansmm sure uuivEHsir i Comparing FloatingPoint Numbers With IEEE 754 oatingpoint representation minor rounding errors can occur 39n calculations We compute 11 ys 1 Multiplying 11 1the result is 11 2 Adding 1 11 times the result is 10999999 These values will not compare as equal using the equality opera or We get similar results when assigning the same value to a oatvariable and to a double variable then comparing the values mu snumERN Pnunscumc 51sz umvsnsm Output d1 10999999999999999 d2 11 d1 and d2 are not equal piF 31415927 pid 3141592553589793 piF and piD are not equal Topics m ngki mm 12 Comparing 7 Floating pulrit numbers 7 omens 7 Strings Conditional Operator 1 8 1 m w daubled21 117zanvme11 1 EDWnl m my CD Wnl 7 oaz n m 77m 39 cu wnl d12md22mequ2l i mszsmsxswav 31o15925535xs793 cu wnl we m cu wnl w 7 own n pl pin cu wnl mmwum em 1 else 3m snumsan anzcumn sms unlvERslTv Solution Choose a small threshold value how close should the values be to be considered equal If the difference between the two values is less than the threshold value then we will considerthe two oatingpoint numbers to be equal Hint use the MathAbs method to compute the difference Sm snurNERN Pomscumc 5an umvERsm mu snumsau museum smz UHNERSl n Output laws 392 mm d1 10999999999999999 c 0 WW 5 92 9559 9919 99 d2 1 c 0 WW 5 92 a 2919 d1 and d2 are considered equal u Part 2 Compare oat and awe W some value last or 9m592559599799v ewe m9 91592559599799 c Owln npi w piF 31415927 ffM ll L ZE pw pll il mm pid 3141592553589793 els WWWWpmammswemum piF and piD are considered equal C OWlVi PlFBnd piDare not equal 5m S uYHERN anscmu 5m uiiithsir i w snurusm PDLVTECHNIE snrs univERsm39 Comparing Floats Comparing Characters Problematic given roundingprecisi 9n 5 Pickatoleranceand ifthe difference betvveenthe numbers What does 39t mean to compare 2 l5 less than this tolerance considerthe numbers equivalent characters 1i Mathahs d1 d2 lt THRESHOLD Is a lt cwLquotd1 and 92 are consldered equalquot islA yZ else cwLquotd1 and 912 are not equalquot mu snurHERN pnmscumc 51sz umvERsm 3m snumERN anzcumc sms uulvERslTv Lexicographic Ordering Because all characters are encoded Comparing Objects The equality operator compares using the Unicode encoding scheme Obledm Unicode values are com d Example 39 39 39 39 39 IN and d2 are two Date object Llexdcggrtf prl w menng 395 quotm smzt39y references then d1 d2 evaluates to a p a 6 quotE W 6 upperc e a true only in and d2 point to the same lowercase characters are mixed object that is the same m The equality operator does not compare the data month day and year Ethose objects we SOUTHERN POLYTECHNIC STATE UNlVERSiTV Comparing Object Data boolean equals Object obj returns true if the data of the object 0M is equal to the data in the object used to call the method With d1 and d2 Date object references d1equals d2 Returns true ifthe month day and year ofd1 equals the month day and yearof d2 SOUTHERN PDLYTECHNIC STATE UNNERSiTV Comparing Date Objects mu SOUTHERN PDLVTECHNIC STATE UNlVERSlTV The Conditional Operator The conditional operator contributes one of two values to an expression based on the value of the condition Some uses are handling invalid input outputting similar messages Syntax condition 7 trueExp falseExp If condition is true trueExp is used in the expression If condition is false falseExp is used in the expression Spw SOUTHERN PDLYTECHNIC STATE UNlVERSlT f instantlate two Date Objects wlth 1dent1cal data Date 11 new Date 4 10 2006 Date d2 new Date 4 10 2006 assign object reference d1 to d3 Da d1 13 now polnts to dl instantiate another object wlth different data Date 4 new Date 12 1 DO L n 39 139 use the eonss method SOUTHERN POLVTECHNIC STATE UNlVERSlTV compare references using eaaaiiey operator if i ai 2 mm quotdl ana a2 are equalnquot eiee Cle Ll quotd1 ana a2 are not equalhnquot it i ai a3 c ml quotan and as are equalnquot eiee cnL quotan and as are net equalhnquot compare object data uslng tne equals method f1d1equalstd2ii cth at data and a2 data are equaln i all data and a2 data are not equaln i if 1 d1equalst d4 H c a WM 1 data and a4 data are equal l d date and a4 data are net equal l 8pm SOUTHERN PDLVTECHNIC STATE UNlVERSlTV Equivalent Code The following statement stores the absolute value of the integer a into the integer absVaue int absValue a gt0 2 a a The equivalent statements using ifese are 1nt absValue if a gt o absValue a else absValue a39 mu soumsau pnmscumn smz univzasirv Nested if Statements Sm sourNERN Pomscumc 5an umvERsm The Conditional Operator Another exampb ifstatements can be written as part ofthe true or false block of another ifstatement c 0 1n quotYour change 15 quot count CO nt 2 1 quotmmquot iDimeS Typically you nest Ifstatements when more information is required beyond the results of If count equals 1 then quotDimequot is the rst ifcondition n39nted The compiler matches any else clause with the most previous ifstatement that doesn39t already have n else clause Ifcount is anything other than 1 then quotDimesquot is prin e You can use curly braces to force a desired ifelse pairing w snurusm pnmchmc snrs lnivERsm 5950 soundan anmmn sure univEnsm Another Example 2 ilxr Example 2 y x cow1n quotx and y equal 2quot y xi else Comnl quotx and y Equal 2quot i cow1n quotx equals 2 but y does notquot E Jae Comnl quotx does no Equal 2quot i With curly braces added the else clause is The else clause is paired with the paired with the rstifthat is if x 2 second if thatis if lt y x gt 3m snumsan anzcumn sms ulllvERSlTv mu snumsau pnmscumc 51sz mlivERsm The quotDangling elsequot A dan ling else is an else clause that cannot be paired with an ifcondition l In the absence of braces 2 quotLlux am y ma 2 M an else is always paired with the closest preceding if that else pelted Inch l x r 2 l doesn t quot already have an else paired with it else nu mmmng m comn quotx am y are nor equalquot i Generates the compiler error 39else39 without 39il39 Sm snumsau PDLYTECHNIE 5an unwmm Bad Example has output FAIL no1 lvurInu lvurluo 10011 If Imus gt mu If Ivarg lt 1nn covnn IrulnllPASSquot IIISI GOWIII FAILquot WHY The compile ignores inde tation and pairs the else wit 5m saumsnu anscunn sms unwi sm The switch Statement Sometimes the switch stateme t can be used instead ofan ifelseifstatement for selection e t be comparing the value ofa character char or integer byte short or int expression to constants ofthe same types n h the second if 3m snumsau museum 5mg UNNERSlTquot To correct the problem use braces oatmun Ivarnu 1onu n Ivorno gt no0 quotnr mu commonrain masquot Ila 00Wllll HFAILquot w snurusm PnLv rEciml sws iquRsm Syntax of switch switch c integer expression case constantl etatemente optional case Cons t2 s atementsi hre k ptiunal defaul optional t statement e susu wnvgazwmm Operation of switch The expression is evaluated then its value is compared to the case constants in order When a match is found the statements under that case constant are executed in sequence until either a break statement or the end ofthe sw1tch block is reache Once a match is found ifother ants are encountered before a break statement then the statements for these case constants ar also executed at 3m snumERN anscumn 5mg univERsiTv Some Finer Points of switch The break st tem s are required Theirjob is to terminate execution ofthe switch statem The default label and its statements are optional They are executed when the value of the expression does not match any ofthe case constants The statements under the case constant are also optional so multiple case constants can be wri ten in sequence if identical operations will be performed for those value You cannot perform relational checks with a switch statem nt Sm Saul m PDLVTECHNIE s39ms vaERsm Example a Simple Calculator Prumptuserfurtvvu doublesmum numZ and a char operallonvvlwlcl1 can be a fur addltlun ur s fur subtractlun swltch Bperatlun mu snumERN museum smz unwzasm A Caselnsensitive Calculator svnutch lt Bperatlun InI wugmlnPnunds 155 onquot welgm ml uxaranterr pmmmma wmmm C0WlnMHngnPnunds n Dnunds l mak cowln1sn t wugManmds n mince l mak C0WlnMHngnPnunds l22 n hlns l mak cowln 5 n welngnPnunds n on D mak netuh cowlnr nm mm mm mnnled l mak II ummun marg In upan nr andquot quotgut IIulh mu mm us 25 m 1m hm c can an ur 1 Dan I c ens1W m 150 at nun m a Illnd much DDWII Lm lemnq at H m m bulb my mu snumERN museum 5mg umvERsm I u mm amp can can 139 cown qumng hut ulnar pgmlquot x m maul cowm mu Idltmdl mm lll Ind uch W 5mm mm 5mg uulvERslTv Now It s YourTurn Time for some group work Sm sourNERN eomscumc 5an ImeRsm WrIte an expreSSIon for each age ts from mm 21 thetustve water is iess than i 5 and is aisn greaterthan Eli year ts divisibie by4 epeeet ts hut gteatetthah 55 Whte a tegteai asstghrheht statement tut each at the tettewth asstgh a vaqu uftrue In between tt n ts th the range EIka tn up inEiUSWE ethetwtse asstgh a vaqu ettatse asstgh avaqu uftruetu uppercase ts ehts ah uppercase tetteh uthErWtsE asstgh a vaqu ttatse asstgh a vaqu uftrue tn ameee ttm ts a divisur at p ethetwtse asstgh a vaqu ettatse mu soumsau PoLvTEcuNIn smz umvz sm Write IfThen or IfThenElse for each If taxCode is T increase price by adding t axRate times prIce to it If code has value 1 calculate and display taxDue as the product of income and taxrate IfA is strictly between 0 and 5 set B equal to A othenNise set B equal to A sourHERu ansmm w snurusm PDLVTECHNIE Sm mt mttteesm So me A nswers if taxCode 139 price price taxRate 39 price ifcode 1 taxDue incom e taxRate C0WlntaxDue snrs uutmwv Remaining Answer if Agt0ampampAlt5 E 1IA mu snumsau pnmscumc 51m umvERsm we soumERN PoLv rEcuNI snrs umvERsz What s the output and Why int age age 20 ifage16 C0Wln Did you get driver s licensequot What s the output and Why int age age 30 if agelt 1s C0Wln Do you drivequot C0Wln Too young to votequot Sm snumERN Pomscumc mu snumERN PnLvTEcuNIn s39ms unwsnsm smz ummwv What s quot 9 utPquott39 and WW What s the output and Why hoolean code If X gt w code false X X 103 if U code lsoewln x biggerquot C0Wln Vesterdayquot C0Wln x srmllerquot else C0Wln y is y C0Wln Tormrrowquot sourNERN Pomscumc 39w S UTNERN PDLVTECHNIE 5W snrs unwsnsm Lecture GB M ore Repetition Briana B Morrison a Fxgures rm Lewis cu So aaxe Snluuanf Adam Wesley 5m saumsau anscum 5m umvEHsm int count for count 0 count lt 10 count COW quot smz unwz sm Overview In nite Loops again Loop patterns common tasks Sentinel loops Nested Loops Examples snurHERN pnmzcumc 393quot sms mleRsm OUTPUT NOTE the10 asterisks are all on one line Why 53 mm mumsquot ems mnvERsm soumERN Pou rzcumc 395quot sms umvERsm What s the output from this loop int count for count 0 count lt 10 countH comW O U TP UT no output from the for loop Why the right after the means that the body statement is a null statement in general the body of the for loop is whatever statement immediately follows the that statement can he a single statement a block or a null statement actually the code outputs one after the loop completes its counting to 10 Sm snurNERN Pomscumc 5an umvERsm mu soumsau PoLvTEcuNIn smz UNIVERSITY What does this loop do INFINITE LOOP O The semicolon indicates an empty lo p 39 ody 1 is never executed because it is not part ofthe loop body so the condition is always true int i While l iltlO39 Avoid putting a semicolon a erth i condition of a while loop Doing so creates an empty loop body and could result in an endless loop 5m saumsnu anmmn sure univEHsm svxuziiEH5iie22wm The Endless Loop Looping Techniques also called an Inite loop Ifthe loop condition never evaluates to false the loop There are standard patterns and body is executed continuously without end teChn39ques for Performmg these Ifthe loop body has no output the endless loop common operanons39 makes the computer appear to h g Accumulation Ifthe loop body p uces output the endless Couming quotems I op results in that output being repeatedly written without end F39quotd39quot9 3quot Average Aborling the program will interrupt the endless loop Finding Maximum or Minimum Values u snumERN Pnunscum 51m umvERsm SiSU A TE 5 i5eE2W C quot39E Accumulation Accumulation Pseudocode eet total tu u vety 1 e h l Approach the runningtotal read a number priming read We start by initializing atotal variable to 0 while number 15 we the sentinel value Each time we read a value we add it to the i total add the humhet tu total e have no more values to read the total is complete Note that this is the same pattern used by the grocery cashier uutput the total teeu the next number update teeu Sm snurNERN Pomscumc 5mg umvERsm mu snumERN pnmscumn smz univzasm Counting Items Forgetting to initialize to 0 before beginning the total variable the loop will produce incorrect results Approach the running count We start by initializing a count variable to 0 Each time we read a value we c ec whether that value meets the criteria as some hing we want to count If so we increment the count variable b 1 hen we are nishing reading values the count is complete 5950 saumsnu anmmn 5m univEHsm w snurusm pnmchmc snrs univERsm Counting Items Pseudocode aet teuat te u teau aaput priming read Forgettingto initialize the countvariable whale aaput aa pet the aeptapea value to 0 before beglnmngthe loop w t produce incorrect results 1f ahput 15 what we want te count auu 1 te count teau the next luput upuate teau i uutput c uuht mu snumERN pnmscumc 51sz umvERsm W eauueaa panacea sms univERsiTv Calculating an Average Approach combine accumulation and nting te u a humhet We start by initializing atotalvariable and Th1 e mm is quotat the gamma value countvariablet Eac ti n item we add it auu the humhet te total 5 auu 1 te the count value to the total variable and increment read the next number he count variab When we have no more itemsto readw eee average to total c ne calculate the average by dividingthetotal a quot tzn 39 quot13 mt by the count ofitems cuuht uutput the averag e sum SOUTHERN PDLYTECHNIE STATE UNIVERSITY Forgetting to check whether the denominator is 0 before performing division is a logic error svsu Correct Calculation Remember that if we declare total and count as integers then average will be calculated using integer division which truncates the remainder To get a oatingpoint average we need to type cast one of the variables either total or count to a double or a float to force the division to be performed as oating point Example double average double total count SnSU SOUTHERN POLYTECHNIC Spw SOUTHERN PDLVTECHNIC srArE UNIVERSH V STATE UNlVERSlTY Finding MaximumMinimum Values Approach the running maximum or minimum Forthe maximum minimum is similar Read the rst item and save its value as the urn Initializing a maximum or a minimum to an arbitrary value such as 0 or 100 is a logic error and could result in incorrect results For example if we initialize the maximum to 0 and all the values read are less than 0 then we will incorrectly report 0 as the maximum Similarly if we initialize the minimum to 0 and all the values read are greater than 0 then we will incorrectly report 0 as the minimum current maxim Each time we read a new value we compare it to the current maXImum lfthe new value is greater than the current maximum we replace the current maximum with the new value When we have no more items to read the current maximum is the maximum for all values 395 SOUTHERN PDLYTECHNIC STATE uNIvERSiTv A Sentinelcontrolled Loop requires a priming read initializationthis means you read one set of data before the while SM SOUTHERN POLYTECHNIC STATE UNIVERSITY 777777777 quot7 SentinelControlled While Loop 1n1t1allze variables priming read read the first data 1tem test if not sentinel value whlle item is not the Sentinel value i update is another read Sentinel values same data type as value read must tell user the sentinel value cannot be a valid data value process the item update read read the next data item report the results sum SOUTHERN PDLYTECHNIE 3pm SOUTHERN PDLYTECHNIE STATE UNIVERSITY STATE UNIVERsn v end Example m ount u OW Enter a value gt input l 1D 1D is sentinel value scannextlnt 39 i Omitting the update read may result in an less loop int input 7 while input l lEl El 15 sentinel value quotEnter an integer gt u l inp scannextlnt gt cowin input Hi l If the value entered for input is not 10 this is an COwln endless loop because we never read a new Ifthe user enters the values 20 30 10 then the output will be value for input Thus the condition always quot oun is whic is incorrect We should not process the evaluates to true semmel Value quotcount is quot count SnSU SOUTHERN PDLVTECHNID 33933 SOUTHERN PDLVTECHNIC STATE UNIVERSlTV STATE uvaERsm39 Constructing Loop Conditions Do not check for the sentinel value The loop body is executed as long as inside a while loop Let the while loop the loop condition evaluates to true condition detect the sentinel value So if we want to stop executing the loop when the sentinel value is read the loop condition has to check that the value is NOT the sentinel Thus the loop continuation condition is the inverse of the loop termination condition Ens SOUTHERN PDLYTECHNIC soumERN POLYTECHNIE 5m umvensm 395 5m umvensnv Example Find Sum of 5 Integers Update lnCrement Can Be gt 1 set total to o Print the even numbers fromOto 20 forilt05byl l set output to an empty String fori0t020by2 l read integer add integer to total l append i and a space to output print the total l print the output String 5m snuYNERN Pammmic smz univEnsm For Loop Rules i l t for in t expr1 exprZ sta ement 930 init statement can be null expr2 is optional for inputval 999 input scannextlnt expr1 optional true assumed for coWIn Hiquot init can be a declaration for inti o i lt10 i oca eoope lt 1 saumsm Pnu rEcHNI smz unwinsm 3w snumsau PnLvTEcHNIn smr unwrnsm Loop Control Variable Scope When a loop control variable is declared inside the forloop header it cannot be referenced a erthe loop for1nt1 1lt31 t cow1n i uk COWln 1 error 1 undefined 3m snui HERN pnmzcumc 5mg minRsnv SPSU To Reference 139 After the Loop int i ll declare i before loop fori0ilt3i COWlni COWlni llok snumERN Pnu rEcHNIc 5mg unwinsm Nested Loops Loops can be nested inside other loops that is the body of one loop can contain another loop A while loop can be nested inside another while loop or a for loop can be nested inside another forloop A for loop can be nested inside a while loop and a while loop can be nested inside a forloop Testing for Loops An important test for forloops is that the starting and ending values of the loop variable are set correctl For example to iterate 5 times use this header for1nt101lt571 orthis header for1nt1l1lt571 3m snumERN Pou rzcum 9 51an umszle initialixe inner loop while inner loop condition inner loop processing and update sis i 39l l lgi zhlmwquot saw What s the On ut To de5lgn a nested loop tp I 39 39th t I egm WI 0quot er 00quot print heading COWnquoti tjquot when you get to where the Inner loop appears make it a separate module and come back to its design later fur mt I 0 I lt 4 l forlnt C 0 Win COWln quotOuterquot i i 39 39 nnert j ll end for outer loop m 5m saumslm Pnlvrscmlll mu SnUTHERN PDLVTECHNIE 51an uhwshsm snrs UHWERSlTY Nested for Loop Execution Analys39s The highest numberwe print is the Inner loop executes all its iterations for same as the line number each single iteration ofthe outer oop y 1 Example how can we print this i 1 for number 1 to llne by 1 prlnt number and a space l 4 prlnt a new 11ne 4 l snurHERN Pnu rsclmll snumERN pnmzcumE 5Wquot 51sz wlwsnsm will 5mg umvsnsm Test Yourself How many times is the loop body below repeated Whatis rinted durin each re etition ofthe loo bod 7 Now let 5 work some more loop p 9 p p V examples 3 count 0 while countlt 3 X X X COWnx count Ilend while Sm snumsau PDLYTECHNIE 5an ultwsnsm Test Yourself 39 a 39 39 39 lll aru ofifrorn 1 to 10 Eutthe loop does not work correctly Explain what the problem is and describe how to correct it forintl 0ilt1oi CDWn i Write a Ioopto add alltheodd integers between 1 and n 5950 saurHERN PDLYYEEHNII srArE unwERsln Test Yourself What is the least numher oltimes that the hody ot a while loop may he executed Rewrite the loop so that II prints all multiples ols lrorn n Ihrnugh inn inclusive rouryouno cou 39s learnin t e 39 ly numher system and has askedyoutowr aprooramthat splays all powers onthat are less than a certain value is ay 1nnnn mu snumERN PDLVYECHNIE 5m umvERSih Test Yourself w does the while statement below display Rewrite it as a for statern ent num 10 while num lt 100 C0Wn num num II end while Whatdoes the fors Rewrite it as adowhl 3 n gt o CDWn Ma tatem ent below display i e statern ent nquot n H squared is u thpow n 2 3980 r squotu5tliv s2ir39f quotquot Test Yourself What output values are displayed by the loop below for a data value of 5 CDWn Enter an integer H ParsekbReadLine0 count 0 while countlt A DWn product product product x un 393quot SDUTHERN PDLVTECHNIE 5an vulvsasm Test Yourself Write a flagcontrolled loop that continues to read pairs 0 egers un rea s a p wi the property that the rst Integer in the pair is evenly divisible by the second 3m SnUYNERN ansctmlt 5mg UltiVERSiTY for intj 0jlt i j cowt W CDWn II end fori forintirnigt0i n j gt 0 J39 0W hequot CDWn II end fori 5m snurNERN Pomscumc 5an unwsnsm Write the nested loops that cause the output below to prin SOUTHERN POLYTECHNIC STATE UNIVERSITY Lecture 3A Using Classes Briana B Morrison gee Figures from Lewis C Software Solutions Addison Wesley CSE 1301 33938 SOUTHERN POLYTECHNIC STATE UNIVERSITY ObjectOriented Programming Classes combine data and the methods code to manipulate the data Classes are a template used to create specific objects All C programs consist of at least one class SpSU SOUTHERN POLYTECHNIC STATE UNIVERSITY Some Terminology Object reference identifier of the object lnstantiating an object creating an object of a class Instance of the class the object Methods the code to manipulate the object data Calling a method invoking a service for an object SOUTHERN POLYTECHNIC STATE UNIVERSITY Topics Class Basics and Benefits Creating Objects NET Architecture and Base Class Libraries Random Class Math Class SDSU SOUTHERN POLYTECHNIC STATE UNIVERSITY Example Student class Data name year and grade point average Methods storeget the value of each piece of data promote to next year etc Student Object student1 Data Maria Gonzales Sophomore 35 SpSU SOUTHERN POLYTECHNIC STATE UNIVERSITY Class Data Members of a class the class39s fields and methods Fields instance variables and class variables Fields can be any primitive data type int double etc objects Instance variables variables defined in the class and given values in the object CSE 1301 C SE 1301 SOUTHERN POLYTECHNIC SOUTHERN POLYTECHNIC SIJSU SDSU I STATE UNIVERSITY STATE UNIVERS TY What s in a Class Encapsulation Class contains Instance variables are usually declared to be private which means users of the Members are class must reference the data of an Fields object by calling methods of the class Instance variables Thus the methods provide a protective Class variables shell around the data We call this encapsulation Methods Benefit the class methods can ensure that the object data is always valid snsu f 1 snsu Naming Conventions 1 Declare an Object Reference Class names start with a capital letter Syntax Object references start with a C39aSSName ObJeCtReference lowercase letter or In both cases internal words start with a O C39aSS ame OEJeICtReH Objecl fRefzm capital letter Ebject Ire erence 0 ds address 0 object xamp e Example class Student Dated ObJeCt31 StUden StUdentZ d1 contains the address of the object but the object hasn t been created yet snsu gatHUEtragwE HN39E l mu 2 lnstantiate an Object Date Class API Objects MUST be instantiated before they Constructor special method that creates an can be used object and assigns initial values to data Call a constructor using new keyword Constructor has same name as class Syntax Date objectReference new CIassName arg list dcreatega Date abjectyit igg gl monthr aan earvaueso Arg list argument list IS commaseparated y y I I list of initial values to assign to object data Datel mt mm39 int 010139 WC W l and may be empty creates a Date object with initial month day and year values of mm dd and yy CSE 1301 7 7 CSE 1301 SOUTHERN POLYTECHNIC STATE UNIVERS SOUTHERN POLYTECHNIC STATE UNIVERSITY lnstantiation Examples Date independenceDay independenceDay new Date 7 4 1776 Date graduationDate new Date 5 15 2008 Date defaultDate new Date CSE 1301 SDSU SOUTHERN POLYTECHNIC Objects After InstantIatlon Object Reference independenceDay Owed Ob ect R ferenlte 1 e Instances graduationDate Object Referenc defaultDate 7 i month Object Data CSE 1301 3A14 SOUTHERN POLYTECHNIC STATE UNIVERSITY STATE UNIVERSITY Object Reference vs Object Data Object references point to the location of object data An object can have multiple object references pointing to it Or an object can have no object references pointing to it If so the garbage collector will free the object39s memory CSE 1301 SDSU SOUTHERN POLYTECHNIC STATE UNIVERSITY Creating Aliases Date hireDate new Date 2 15 2003 Date promotionDate new Date 9 28 2004 promotionDate hireDate int X 5 y 3 X y CSE 1301 3A16 SpSU SOUTHERN POLYTECHNIC STATE UNIVERSITY Two References to an Object After program runs two object references point to the same object Object Reference Object Reference hireDate promotionDate Object Data CSE 1301 31517 null Object References An object reference can point to no object In that case the object reference has the value null Object references have the value null when they have been declared but have not been used to instantiate an object Attempting to use a null object reference causes a run time exception CSE 1301 3A1 8 SOUTHERN POLYTECHNIC SOUTHERN POLYTECHNIC snsu snsu m STATE UNIVERSITY STATE UNIVERS NullReference Reusability Date aDate Reuse class code is already written and aDate setMonth 5 tested so you build a new application faster and it is more reliable Date independenceDay new Date 7 4 1776 U set object reference to null Example A Date class could be used in mdependenceDay null a calendar program appointment attempt to use object reference SChedUIIng program onIine Shopping independenceDaysetMonth5 progranq etc snsu if if snsu How To Reuse A Class The Argument List in an API You don39t need to know how the class is Pairs of dataType variableName written Specify You do need to know the application programming interface API of the order Of arguments Data type of each argument class The API is published and tells you Arguments can bei HOW to create objects Any expression that evaluates to the What methods are available SPECified data type How to call the methods SDSU SOUTHERN POLYTECHNIC SOUTHERN POLYTECHNIC STATE UNIVERSITY STATE UNIVERSITY Method Classifications hwe INETexmnmehme Accessor methods Gets the values of object data Mutator methods Writeschanges values of object data Others to be defined later CSE 1301 7 7 CSE 1301 SpSU SOUTHERN POLYTECHNIC STATE UNIVERSITY SDSU SHANEHENINERgiTYYTECHNIC DOt NOtatlon a Use when calling method to specify Method which object39s data to use in the method Method Syntax objectReferencemethodName arg1 arg2 Note no data types are specified in the method call arguments are values only STATE UNIVERSITY i SpSU SOUTHERN POLYTECHNIC SDSU SOUTHERN POLYTECHNIC STATE UNIVERSITY NET Architecture When calling a method include only Framework expressions in your argument list lncluding data types in your argument list will cause a compiler error o If the method takes no arguments remember to include the empty parentheses after the method39s name The parentheses are required even if there are no arguments When you press F5 source code compiled into lL submitted to NET engine for execution SpSU SOUTHERN POLYTECHNIC r n 7 7 H W W N W W 7 i SDSU SOUTHERN POLYTECHNIC STATE UNIVERSITY STATE UNIVERSITY NET Program Execution Base Class Libraries MEXE Need to become familiarwrth libraries to MT use most efficiently 3633 mm Group services under Namespace Libraries UseLfgaes Crsjoader Tfi ft39fsm Most commonly accessed Namespaces Comm 1 are grouped under System Namespace I 3 Platform Execute Specific Application Instructions FIGURE 34 NET program execution SDSU SOUTHERN POLYTECHNIC SDSU SOUTHERN POLYTECHNIC STATE UNIVERSITY STATE UNIVERSITY I I System Contains fundamental classes and base classes that de ne commonly used value and reference data types events and event handlers interfaces attributes and processing exceptions SystemCollections Contains interfaces and classes for various collections of objects such as lists queues bit arrays hash tables and dictionaries M t I 39 t t t t System Data Contains classes for ADONET architecture u S u I I g S a e I I I I O u SystemDataCommon Contains classes for the NET Framework data providers System Drawing Provides access to GDi basic graphics functionality Va I u I n I I b ry SystemDrawingDesign Contains classes that extend designtime user interface logic and drawing Create custom toolbox items type speci c value editors or type converters that can convert values between certain types I u S 1 1 1 g S y S t e m o T e X t SystemDrawingDrawing2D Provides advanced twodimensional and vector graphics functionality gradient brushes the Matrix class used to de ne geometric transforms and the GraphicsPath class I u O r O u n I I u a I SystemDrawingPrinting Provides printrrelated services Printing is covered in 39 Chapter 11 I I System Io Provides synchronous and asynchronous reading and S t T t S t B I d h writing on data streams and les y S o e X o r l n g u l e r p r a S e SYstemNet Provides a simple programming interface for many of the protocols used on networks today n e W S y S t T e X t S t r i n u i l d e r SystemReflection Contains classes for analyzinginternal program structures System Security Contains the underlying NEI39 Framework security system Chan e i s inevi t ab 1 e g I System Text Contains classes representing ASCII Unicode UTF 7 and UTF8 character encodings abstract base classes for converting blocks of characters to and from blocks of bytes System Threading Contains classes that enable multithreaded programming SystemWeb Supplies classes and interfaces that enable browser server communication FIGURE 35 Most Common NET Namespace CSE 1301 3A CSE 1301 33933 SOUTHERN POLYTECHNIC SDSU SOUTHERN POLYTECHNIC STATE UNIVERSITY STATE UNIVERSITY Random Class Random API 0 g e n e O m n u m Constructors initializes a new instance of the Random class using the public Random speci ed seed value if any A good seed to use is public Random nt Seed DateTime NowMillisecond as this will be a G e n e a d O n d O m n u m r random number based on when the program is run a p a O m b pujbnlticm at11quotfatJLzuaeL int Next Sg ggggda ggirrf rative random number less than the ptgilitcn vibrltuai double Returns a random number between 00 and 10 seed value protected virtual double Returns a random number between 00 and 10 Sample FIGURE 36 Some constructors and methods of the Random class CSE1301 7 A 7 CSE1301 SpSU SOUTHERN POLYTECHNIC Spsu SOUTHERN POLYTECHNIC STATE UNIVERSITY Listing 32 STATE UNIVERSITY RandomNumbers cs C Ken Culp I Demonstrates the creation of pseudo random numbers using the numz generator 39 NeXtDOUble 39 Random class Console0utWriteL1ne quotA random double between 01 quot 9 num2 1151119 System namespace RandomNumbers ConsoleInReadLine Wait for enter key class RandomNum static void Mainstring args SystemRandom generator new RandomDate39I ime NowMillisecond To generate a 1 numl double numZ oufput random 1nteger 1 numl generatorNext between a and up Console0utWriteLine quotA random integer quot numl A random integer 1773351873 to bUt n0t numl generatorNext 10 From 0 t0 9 8 including b Console 0utWrLteLLne quotFrom 0 to 9 quot numl From 1 to 10 6 numl generatorNext 10 1 From 20 to 34 20 Console Out WriteLine quotFrom 1 to 10 quot numl From 10 to 9 6 numl generatorNext 15 20 A random float between 01 0 71058085 Console0ut WriteLine quotFrom 15 to 34 quot numl From 1 to 6 3 numl generator Next 20 10 Console Out WriteLine quotFrom 10 to 9 quot numl CSE 1301 7 7 7 CSE1301 SDSU SOUTHERN POLYTECHNIC STATE UNIVERSITY SOUTHERN POLYTECHNIC STATE UNIVERSITY methods Math Class 39 Basic mathematical functions v All methods are static methods class invoked through the name of the class no need to instantiate object 39 Two static constants Pi the value of pi E the base of the natural logarithm Spsu SOUTHERN POLYTECHNIC STATE UNIVERSITY Represents natural logarithmic base speci ed by the constant e Represents the ratio of the circumference of a circle to its diameter speci ed by the constant at Overloaded Returns the absolute value of a speci ed number Acos Returns the angle whose cosine is the speci ed number As in Returns the angle whose sine is the speci ed number Atan Returns the angle whose tangent is the speci ed number Ceiling Returns the smallest whole number greater than or equal to the specified number COS Returns the cosine of the speci ed angle Cosh Returns the hyperbolic cosine of the speci ed angle DivRem Overloaded Returns the quotient of two numbers also passing the remainder as an output parameter Exp Returns e raised to the speci ed power Floor Returns the largest whole number less than or equal to the speci ed IEEERemainder Returns the remainder resulting from the division of a specified number by another speci ed number Overloaded Returns the logarithm of a specified number Returns the base 10 logarithm of a speci ed number Overloaded Returns the larger of two speci ed numbers Overloaded Returns the smaller of W0 numbers Returns a speci ed number raised to the speci ed power Overloaded Returns the number nearest the speci ed value Overloaded Returns a value indicating the sign of a number Returns the sine of the speci ed angle Returns the hyperbolic sine of the speci ed angle Returns the square root of a speci ed number Returns the tangent of the speci ed angle Returns the hyperbolic tangent of the speci ed angle FIGURE 37 Some methods of the Math class SDSU SOUTHERN POLYTECHNIC STATE UNIVERSITY Calling static Methods 39 Use dot syntax with class name instead of object reference 39 Syntax ClassNamemethodName args 39 Example int absValue MathAbs 9 l 39 abs is a static method of the Math class that returns the absolute value of its argument here 9 SOUTHERN POLYTECHNIC STATE UNIVERSITY Listing 33 Quadratic cs Cit Ken Culp Demonstrates the use of the Math class to perform a calculation based on user input using System namespace Quadratic class QuadraticEquation static void Mainstring args I int a b c ax 2 bx c double discriminant rootl rootz Console0utWritequotEnter the coefficient of x squared quot a intParseConsoleInReadLine Console0utWritequotEnter the coefficient of x quot b intParseConsoleInReadLine Console0utWritequotEnter the constant quot c intParseConsoleInReadLine Use the quadratic formula to compute the roots Assume a positive discriminant discriminant MathPowb 2 4 a c rootl 1 b MathSqrtdiscriminant 2 a root 2 1 b MathSqrtdiscriminant 2 a Console0utWriteLinequotRoot 1 quot rootl Console0utWriteLinequotRoot 2 quot rootZ ConsoleInReadLine Wait for enter key SDSU SOUTHERN POLYTECHNIC STATE UNIVERSITY Listing 33 continued Output Enter the coefficient of x squared 3 Enter the coefficient of x 8 Enter the constant 4 Root 1 06666666666666666 Root 2 2 CSElsm Summary What did you learn 39 Muddiest Point snurNERN Pomscumc 3W snumERN pnmscumn smz univzasirv saw me umvERsm Ove rv i ew Lecture 8A Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and arrays Initialization Searching Arrays Briana B lillon39ison a Fegmes rm Lewis cu Sabaaxe Snluuanf Aansm Wesley snsozrwetnveazmm svxuziiEH5ire22wwrim Arrays and Their Properties What arrays look like Hold several values ofthe same type Things to notice homogeneous 1 2 3 4 5 5 number Instant access Linear one after the other There are 7 slots with index numbers 0 6 Static once their size is set its set The name ofthe array is myArray Easy to be off by one Sisquot rsumazwmm 3m awaiteawzcwm Creating Arrays Examples ltdata typegt ltnamegt Anarray ofshorts w ltdata typegt ltsizegt short 1 sonemey new short50 An array of oats floatU lllyBrray new float 25 An array of booleans bool list new boola5 new brings complex variables to life in C Notice that we can create an arra 0 any data type just by changing the data type An array of chars charU characters new enar255 5m snurNERN Pomscumc 5an ImeRsm 3W snumERN pnmscumn smz UHNERSl n Initializing Arrays with Values Modifying an Array data mam ltna gt You must specify which slut you are putting information lrl ne d me w lt ata typegt ltsizegt VALUES Example mu murkan Or o l 2 3 4 49 z mum l Wham 2 Thisvvun tvvurk 2 mu murkan mom 2 ltdata typegt ltnamegt VALUES 333ggmz39gigfm z n Man 0 5m saumsau anscumc 5m uuwsasm w snurusm pnmzcumn snrs uleRsm Accessing Information 39mtia39izmg Arrays large arrays Copying information out of a particular For most arrays you will use a loop to 5ot initialize Exam l 39 Problem create an array of 50 bytes and ll each slot with the number 42 n Age myAzzayH 1 min momma This copies information from the lth slot in in w w slot four into the variable clientAge W 5 om o lt 5n comm uooomu 42 mu snumERN pnmscumc sms umvsosm 3m snumERN Pnurrzcumc sms umvsnsm Line by Line a smaller example Line by Line byle myList new byle539 a for int counter 0 counter byle myList new byte 5 lt 5 counterHM a for int counter 39co myList counter 4239 myList counter 42 nter lt 5 counterH o1234 SW S uYNERN PDLVTECHNIE 39w S UTNERN PDLVTECHNIE 5an unwsnsm smz umvzasm Line by Line Line by Line byte myList new byte 5 byte myList new byte 5 4 for int counter 0 counter lt 5 counterH 4 for int counter 39 counter lt 5 counterH myList counter 42 myList counter 42 Emma Hunter u1234 u1234 ans mysmgzzmmm wsu Line by Line Line by Line byte myLis new byte5 byte myLis e5 for int counter 0 counter lt 5 counterH for int counter 0 counter lt 5 counterH 4 myList counter 42 4 myList counter 42 Hunter Hunter snumsau Pnu rscumc soumERN anzcumn W3quot 51sz umvERsm W3quot sms umvsnsm Line by Line Line by Line byte myList new byte5 byte myList new byte5 for int counter 0 counter lt 5 counterH for int counter counter lt 5 counterH myList counter 42 myList counter Hunter Hunter u u 234 234 SW S uYNERN PDLVTECHNIE 39w S UTNERN PDLVTECHNIE 5an unwsnsm smz umvzasm Line by Line Line by Line byte myList new byte 5 byte myList new byte 5 for int counter 0 counter lt 5 counterH for int counter 39 counter lt 5 counterH a myList counter 42 a myList counter 42 Hunter Hunter D 1 234 ans mysmgzzmmm wsu Line by Line Line by Line byte myLis new byte5 byte myLis e5 for int counter 0 counter lt 5 counterH 4 for int counter 0 counter lt 5 counterH myList counter 42 myList counter 42 Hunter Hunter snumsau Pnu rscumc soumERN anzcumn W3quot 51m umvERsm 393 5m umvsnsm Line by Line Line by Line byte myList new byte5 b e myList new byte5 for int counter 0 counter lt 5 counterH for int counter counter lt 5 counterH myListcounter42 myListcounter muncer Hunter SW S uYNERN PDLVTECHNIE 39w S UTNERN PDLVTECHNIE 5an unwsnsm smz umvzasm Line by Line Line by Line byte myList new byte 5 byte myList new byte 5 for int counter 0 counter lt 5 counterH 4 for int counter 39 counter lt 5 counterH myList counter 42 myList counter 42 Hunter Hunter ans mysmgzzmmm wsu Line by Line Line by Line byte myLis new byte5 byte myLis e5 for int counter 0 counter lt 5 counterH for int counter 0 counter lt 5 counterH 4 myList counter 42 4 myList counter 42 Hunter Hunter snumsau Pnu rscumc soumERN PoLv rEcuNIc W3quot 51m umvERsm 393quot sms umvsnsm Line by Line Line by Line byte myList new byte5 byte myList new byte5 for int counter 0 counter lt 5 counterH for int counter counter lt 5 counterH myList counter 42 myList counter Hunter Hunter SW S uYNERN PDLVTECHNIE 7 39w S UTNERN PDLVTECHNIE 5an uleRslT39r smz UHNERSl n Line by Line Line by Line byte myList new byte5 byle myList new byte5 for int counter 0 counter lt 5 counterH for int counter 0 counter lt 5 counterH 4 myList counter 42 4 myList counter 42 Hunter Hunter also granarwgazwmm mu 2 rE 5 i ls 2er quotquotquot Line by Line Line by Line byte myList new byte5 byle myList new byte5 for int counter counter lt 5 counterH 4 for int counter counter lt 5 counterH myList counter 42 myList counter 42 fals muncer Hunter svsu gavrnvggmm39c am amilazwmm Finding the Smallest Element Another Trace lfyou were given an array ofnumbers how 4 int smallestSoFar W 39d YOU d quot7 smallestSoFar randomArrayW Computers can only compare two at a time f0 Go through entirelist Keep track of smallest so far L t smallestSoFar randornArraycounter 39 e S assume 7 We have an array or 5 integers W e Tne array contains random unknown numbers WW 7 Tne narne or the array is called randornArray u mummy SW S uYNERN PDLVTECHNIE 7 so S UTNERN PDLVTECHNIE snrs umvERstr39r m unwzasm Another Trace Another Trace mt smattestSoFar rnt smattestSoFar srnauestSoFar randomArrayO srnauestSoFar randomArra 0 tor rnt counter 1 counterlt 5 counter tor rnt counter 1 counter lt 5 counter t rr srnattestSorar gt randomArraycounter at rt smattestSoFar gt randomArraycounter a e rn testSorar ranoornArrayrcounterL Sm H StSoFarrandomArra counterL r for u r for u 1 2 1 4 mnemrar 1 2 3 4 smattestSaFav 950 E 5r rvs392ni cquotquot39 W trE 5 rvE2nV cquotquotquot Another Trace Another Trace mt smattestSoFar mt smattestSoFarr srnauestSoFar randomArrawa srnauestSoFar randomArrawa tor rnt counter 1 counterlt 5 counter tor rnt counter 1 counterlt 5 counter rt srnattestSoFar gt randomArraycounter rt srnattestSoFar gt randomArraycounter srnauestSoFar randomArra counterL 5 anestSoFar ranoornArrayrcounterL W for u 1 2 3 4 New warmer SD30 1 r gquot5 rv 2n quotquot39 3m 2 1urm rtgszwmquot39 Another Trace Another Trace mt smatteStSoFar rnt smattestSoFar srnauestSoFar randomArrayw srnauestSoFar randomArrawa fornntco n 1 er rntcounter rlt tf rnaHestSoFargtranoornArraycounterr tf5 attestSoFargtranoornArrayrcounterDt srnauestSoFar randomArra counterL 4 srnauestSoFar ranoornArrayrcounterL m Hunter yrr Hunter 1542gt177 snettestsurer for u 1 4 snarresmrav SW S uYNERN PDLVTECHNIE 7 39w S UTNERN PDLVTECHNIE 5an umvERstT39r smz uuwzasm Another Trace Another Trace mt smattestSoFar rnt smattestSoFarr srnauestSoFar randomArrawa srnauestSoFar randomArra or tor rnt counter 1 counterlt 5 counter tor rntcounter t counter lt 5 counter rt srnattestSoFar gt randomArraycounter rt srnattestSoFar gt randomArraycounter srnauestSoFar randomArra counterL srnauestSoFar randomArra counterL r for for u 1 2 3 4 New warmer 5m snumERM PDLYTEEHNII 3m snumsau pnmzcumc s rArE urtwsnsm snrs urtwsnsnv Another Trace Another Trace mt smattestSoFar mt SmaHestSoFarr randomArrawa a e randomArrawa r 1 counter lt 5 counter u ter 1 counter lt 5 counter srnauestSoFar ranoornArrayrcounterL W for o smattestSorar randomArraycounter ts 17 gt 427 ter 1 2 3 4 smattestSaFav smattestSaFaV SD30 t syrr mznvm39 3m it t ws39a zwmwquot Another Trace Another Trace mt smatteStSoFar rnt smattestSoFar srnauestSoFar randomArrawa srnauestSoFar randomArrawa ror rnt counter r counterlt 5 counter tor rntcounter t counter lt 5 counter rt srnattestSoFar gt randomArraycounter rt 5 attestSoFar gt randomArraycounter srnauestSoFar randomArra counterL srnauestSoFar ranoornArrayrcounterL W W for u 3 4 New warmer SW S uYNERN PDLVTECHNIE 7 39w S UTNERN PDLVTECHNIE 5an umvERstT39r STArE trurvzasmt Another Trace Another Trace rrrt smattestSoFar rnt smattestSoFar 5 HestSoFar randomArrawa srnarrestSoFar tandornArra 0L tor rnt counter tr counter lt 5 countert tor rnt counter t counter lt 5 counter rt srnattestSoFar gt randomArraycounter rt srnattestSoFar gt randomArraycounter rnarrestSoFar ranoornArrayrcounterL srnarrestSoFar ranoornArrayrcounterL Is 17 gt 87 r r for for El 3 4 smattestsaFar El 3 4 smattestsaFar 950 E 5r rvs392ni cquotquot39 W trE 57tr E2trV cquotquotquot Another Trace Another Trace rrrt smattestSoFar rrrt smattestSoFarr srnarrestSoFar randomArrawa srnarrestSoFar randomArrawa tor rnt counter tr counterlt 5r countet tor rnt counter t counter lt 5 countet rt srnattestSoFar gt randomArraycounter rt srnattestSoFar gt randomArraycounter srnarrestSoFar ranoornArrayrcounterL 5 arrestSoFar ranoornArrayrcounterL W W for u warmer warmer SD30 Equot5 rvg392tr quotquot39 3m irrttrrtgrzwmm Another Trace Another Trace rrrt smatteStSoFar rnt smattestSoFar smattestSoFar tandornArra 01 srnarrestSoFar randomArrawa tor rnt counte it nter 5 r 4 tor rnt countert counterlt5r counter rt arrestSoFar gt randomArraycounter rt srnattestSoFar gt randomArraycounter srnarrestSoFar tandornArrawcounterL srnarrestSoFar ranoornArrayrcounterL m W for o 1 2 3 4 smattestSaFar smattestSaFar SW S uYNERN PDLVTECHNIE 7 39w S UTNERN PDLVTECHNIE 5an umvERstT39r STAYE UHNERSlTi Another Trace Another Trace int smallestSoFat int smallestSoFar smallestSoFat ranoornArrayroL smallestSoFat tandomAtta oi tor rnt counter tr counterlt 5r countet tor rnt counter t counter lt 5 countet rt smallestSoFat gt ranoornArraycountert rt smallestSoFat gt tandornAttaycountet t smallestSoFat tandomAttaycountetr r a gt 47 allestSoFat randornAttaycountet r a r fot fot u 3 4 warmer u 1 2 3 4 warmer 950 2E 5 rvs392tri cquotquot39 W trE 5 i39tE2trV cquotquotquot Another Trace Another Trace int smallestSoFat int smallestSoFarr smallestSoFat ranoornArrayroL smallestSoFat tandomAtraywl tor rnt counter tr counterlt 5r countet tor rnt counter t counterlt 5r countet rt smallestSoFat gt ranoornArraycountert rt smallestSoFat gt ranoornArraycountert smallestSoFat tandomAttaycountet srnarrest o attandomAttaycountet W W fot o 1 2 3 4 smallestSaFav smallestSaFav snumERN pnmscumc snumERN Pnu rzcumc 5Wquot 395quot sms uurvsnsm 51m umvERstr r AnotherTrace Summary rnt SmalleStSoFarr smallestSoFat randornArrawa tor rnt counter r counterlt 5 countert rt SmallestSoFar gt tandomAttaycountet smallestSoFat tandomAttaycountet 39 Creating arrays always f W5 a format r W You can create an array ofany type To initialize or search arrays you ll almost always use a loop Arrays hold values that are all the same pe Arrays are static in size fot o E WE snumsau rnmzcumc sws uNivasm 5m snumsrm rnmscumc sws wivinsm Agenda Lecture 1 Hardware and So ware Analog amp DIgItal Binary and Data Representations Introduction Introduction to ComputerArchitecture Briana B Morrison Figures rm Lewis cu Samar Sniuuanf Adam Wesley W3quot Snm HERN Pnu rscumc WW snumERN anscum sms univEnsm sms UlllVERSlTY Computer Processing Hardware 4 The stuff you can touch Soltware Programs and data mm Main 1 W Manith mum u A unwrmea vlcw at mum svmm 3m suurusau anscumn smz uquRsm mu Modern Computer Hardware and Software Hardware the physical tangible parts ofa computer keyboard monitor disks wires chips etc So ware programs and data a program is a series of instructions A computer requires both hardware and are Each is essentially useless without the other mu snumsau rnmzcumc 51an uNwEasirv 5m snuTHEaN mmzcumc smrE wwznsm Basic Computer Concepts Hardware Central Processing Unit Memory and Storage Devices Operating Systems Application So ware Computer Networks and the Internet mu SnuTHERN PnLv rEcHNIc 5mg univEnsirr m mumm I I c 9 Hardware A typical computer consists of CPU executes the instructions ofthe program Hard disk stores instructions and data so program can be loaded into memoryand Memory unit stores the program instructions and data while executing Keyboard and mouse used for data input Monitor used to display output from a program Other accessories peripherals WW snumERN anscum sms umvERslTv CPU and Main Memo promn mnde 1 mini mum 4 i Sun unusPAnc lll 5m suumsau anscumn smz uquRSlh soumsau museum 50 snrs imiszle Input Output Devices s lf39dlwlmhdllm innmumquot I ha 171 1 Ln V m it it 4w mm Sm snurNERN PDLVTECHNIE 39 mu snumERN museum 5an unwsnsm smz unlvzasm The Central Processing Unit The Central Processing Unit A CPU is on a chip called a microprocessor 39 Th CP I I 39 It continuously follows the fetchdecode execute cycle RI IVI Ill Ill nltllull Mm mllll mlmary Pmolms ulculmns and mlkn nmlom willman ML cnumlnuus prowling up Small mug um curry mmquot nutmin Miam Inimmnn Inm m ls 5m S UYHERN anscum sms unlvEHslr l w snurusm PDLVTECHNIE sws ummsm central PIOCBSSIVIQ Unit CPU Processor Instruction Set Arithmetic Logic Unit performs integer arithmetic and logical operations Move data from one location to another Floatingpoint Unit performs oatingpoint 39 Perform a calculation Operatlons Chan e the sequence ofinstructions to ardware registers store data and memory execute the ow ofcontrol addresses Instruction pointer keeps track of current instruction to execute Examples Intel Pentium 4 Sun Microsystems SPARC IBM PowerPC slsu mortallva slsu 2 5IIIUE39E 2W CW39E CPU Speed Memory or Storage Devices Rated in MHz or GHz In one clock cycle a CPU Memory consists of cells that hold one bit fetches an instruction from memory A bit5 value can be 0 or 1 0 decodes the instruction r A byte is 8 binary digits bits executes the instruction Pipelining allows overlap ofoperations to improve performance 2Ghz CPU can execute 2 billion instructions per second mt mu snurHERN Pnunscumc 51sz umvERsm mm mm Ma mm as 2 13143324 tum1 m 2 1 oss nmtve new LII mm of hmarv smug me Dell soumERN Pou rzcumc 395quot sms uulvERslTv m Mammy has width W Wurd size mm Mammy has jg capacity 92 emu ms or mum in Amman um mnmw mum 0504 ma page vluu m mm m oustcum mm Haul m Mmary mum W3 snumERN PoLvTEcHNI sms utilvERSll t39 M emory Main memory is volatile stored information is lost ifthe electric power is removed Secon ary memory devices are nonvolatile Main memory and disks are direct access devices information can be reached directl 39 d random access often A ma netic tape is a sequential access device since its data is arranged in a linear or er you must get by the intervening data in order to access other inform 39 n snumaau anscumc mo 5mg umvERslrv Software Categories Operating System Resource managercoordinator Shell Interface between the OS and the user and applications Applications What the user sees 50quot mm mam 5mg umvERsm 2 mu x977 lem r u r M J lie mm new mum ol mm my mum mm min Demonquot mm 1 sum tumouruni 3m snumsau anzcum smz umvERlev Operating System Software boots when computer is turned on and runs continuously Controls the peripheral devices disks keyboard mouse etc Supports multitasking multiple programs executing simultaneously ocates memory to each progr m Prevents one program from damaging another program Example Microsoft Windows Linux 53 5mm mm W 5mm mm 51sz umvsnsm snrs uulvERslTv Application Software ClientServer Written to perform speci c tasks Runs quoton top of39 operating system Examples word processor spreadsheet database managem system games Internet browser etc What is the 08 here What is the application here does data live How to we coordinate the application among many users U snumERN PoLvTEcHNI W snumaan anscumc sms wivERsii r 5m univERsll v igtgtgtgtgt t9 WW Scum m Am 5w or m sauna m mm 1 A sound we m an nluuanlt mm signal that vlvvuenxs m WM Analug mfurmatmnxs cuntlnuuus piglet information is discrete 505quot SDUYNERN pnmscumc 3m snurNERN Pomzcum 5mg umvERsm san umvERsih imam m at M Sampling induces losses Humans can hear W ZEIHerEIkHz Raw l LI I L wing Wm mm mm 44 1 kHz typical sample rate CD m i we Sample rate gt V duuble frequency rNyquxst 1924 mm 1 A A mm signal V mm mm l Snmnlmlvulws u u 39 to NEW u 4 Digitizing an analog mar by nmulm W sourNERN manic W soumsnu mmmm 5an umvERsm smz univzasirv Why do we care Digital Information Computers are dumb Computers store all information digitally They re just dumb at a really fast rate 28gHz computer can perform 28 billion operations per second Men can perform one Women can perform two Computers only see in binary 01 Anything we see as meaningful is strings of 0s and 1s 7 text 7 graphicsandirnages 7 video 7 audlu 7 program instructions In some way all information is digitized broken down into pieces and represented as numbers 930 E 5 ivg 2l c quot39 WW tr2 5 t39tg392w cquotquot39 Representing Text Digitally Binary Numbers For examme every character is stored as a number Once information is digitized it is represented and including Spaces digquot and puncma Ion stored in memory using the binary number system Corresponding upper and lower case letters are A Slngle bmary dlgquot 0 or 1 IS called a b separate characters Devices that store and move information are chea er and more reliable ifthey have to represent HI Heather onlywostates A single bit can represent two possible states like a light bulb that is ei her on 1 or off 0 Permutations of bits are used to store values snurHERN pnmscumc soumERN anzcumn 593quot 51m umvERsm 395quot sms uulvERslTv Data Representation Converting amp Bases Binary Numbers Binary Expressed in base 2 system two values Oct are 0 and 1 Dec Hexadecimal Numbers Base16 system used as shorthand for binary numbers Representing Characters with the Character Se Sm snurNERN Pomscumc mu snumERN pnmscumn 5an umvERsm smz UHNERSl n Binary Equivalents of Decimal Numbers Powers of Decimal Binam Eguivalent Decimal o 0000 W saumsnu ansmm w snurusm PDLVTECHNIE 5m uuiansm snrs univERsm Decimal base 10 numbers A decimal number can be represented as the sum of powers of 10 the base with coef cients in the base 10 alphabet 0 9 For example 24 5 2000 400 80 5 24B52 10004 100B 105 1 24852 1034 1028 1015 10 slams I 1 m mmva m a and mm m numhu ulnum m m in regimental mu snurHERN pnmscumc snumERN anzcumc 5mg umvzasm 395quot sms univERsiTv on e 39 9 rom may 0 Converting From Decimal to Binary DeCImal Just as a decimal number can be 101101 represented as a sum ofpowers of 10 the base with coef cients in the base 10 alphabet 0 to 9 A decimal number also can be represented as the sum ofpowers of 2 the base ofthe binary system with coef cients in the base 2 alphabet 0 and 1 So we need an algorithm to do that Sm snurNERN Pomscuuic 5an univsnsm Converting From Decimal to Binary 1 Find the largest power of 2 that is smaller than or equal to the decimal number Subtract that numberfrom the decimal lnsert1 in binary number for position equivalent to that power of 2 Repeat 1 3 until you reach 0 5m saumsim PDLYTEEHNII sure umvEHsir i Example convert 359 to binary 5 Largest power of 2 that is smaller than 39 is 32 25 6 39 32 7 so 359 2E 1 251 251 7 Largest power of 2 that is smaller than 7 is 4 22 8 7 4 3 mu smmisim PDLVYECHNIE 51sz umvERsrr r Our results Finally insert missing powers of2 witii coef cient 0 Thus 359 291 27 0 291 25 1 2 0 230 2T1 21 1 291 Removing powers of2 we get 1 o 1 1 o r 10110 0111 mu snumERN PDLVTECNNIE smz ll lVERSl n Example convert 359 to binary 1 Largest power of 2 that is smallerthan 359 is 256 2B 2 359 256 103 so 359 281 103 3 Largest power of 2 that is smallerthan 103 is 64 2B 4 103 64 39 so 359 251 25 1 39 continued on next slide 393quot SnUTHERN PDLVTECHNIE 5mg univsasirv Example convert 359 to binary 9 Largest power of 2 that is smallerthan 3 is 2 21 103 2 1 so 359 251 251 251 21 21 1 1 11Largest power of2 that is smallerthan or equal to 1 is 1 2 121 1 0 so we are nished 3m snumERN anzctmii sms unlvERSlTv Hexadecimal Numbers Base16 number system Uses digits 0 9 and letters A F One hexadecimal digit can express values from 0 to 15 For example C represents 12 Thus one hexadecimal digit can represent4 bits Sm snurNERN Pomscumc mu snumERN PnLvTEcuNIn 5an umvERsm smz univzasirv Hexadecimal Binary Equivalents Examples Hex Binary Hex Binary Binary number 0 0000 3 100 Hex equivalent 1 0001 9 1001 2 0010 A 1010 Binary number 3 0011 B 1011 4 0100 c 00 Hex equivalent 5 0101 D 1101 6 0110 E 1110 7 0111 F 1111 0001101011111001 1 A F 9 1011001110111110 B 5m saumsnu anscnm sure uuiyEHsir i The Unicode Character Set Each character stored as 16bits Maximum number ofcharacters that can be represented 65536 215 w snurusm PDLVTECHNIE sws mivERsm ASCII character set used by many pro ramming languages stores each character as 7 bits maximum number of characters is 128 For compatibility rst 128 characters of Unicode set represent the ASCII characters Sm snurNERN Pomscumc mu soumERN pnmscumn 5an umvERsm smz UNNERSl n Topics Lecture 48 39 Me hws Return Parameters Constructors Overloading Constructors Briana B Mon39ison 39 Scope Writing Classes Fxgures rm Lewis cu Samar smmm39 Adiison Wesley 5m saumsnu anmmn w snurusm pnmchmc sure univEHsir i snrs univERsm Method Declarations Methods Let39s now examine method declarations in more derail Used to group a set of instructions A method declaration speci es the code that will 39 Give a name 5 we can referto it later be executed when the method is invoked called This name represents the instructions When a method is invoked the ow of control Methods can be public or pri at jumps to the method and executes its cod v e Public if someone outside the class should access nvoke them Private if used internal to the class When complete the ow returns to the place where the method was called and continues The invocation may or may not return a value depending on how the method is de ned 2m mu snurHERN pnmscumc 3m soumERN anzcumn 51m umvERsm sms univERsiTv Method Control Flow Method Control Flow If the called method is in the same class 39 The called memOd i5 O equot Part Of Other only the method name is needed Class 0quot ObieCt J Sm snurNERN PDLVTECHNIE 5an umvERsm A Method Returns When the method is done control returns to where we lelt offquot in the caller As in math functionsmethods can evaluate to som We should be able to return a value The return statement halts execution within the method and optionally returns 5m saumsnu anscum sms umvEnsm Method Header A method declaration begins with a method header aha cm um um um um suan quot2553qu l quotMMquot Parameter um return The Darameterllst Sveanes may mm and name nfead parammr The name of a parammr u the method dedaratmn 5 alled aformalparameter mu snumERN museum smz UHNERSl n Return Example int sumint a int 11 quotmm a h Cnnsnlewritelin9 1 his will never be displayed w snurusm PDLVTECHNIE sws MINERle Method Body The method header is followed by the method body max 0316 um um Int mm sumq mssaqel ml sum mlml mlmZ max xesull messagechalkltslll0 5m and mm xeunn xesull mind data They are quotand The return exvresslnn must he nuslslent mm are a the return tyne n finishes exeultlllg snumERN pnmscumc 593quot 51m umvERsirw Method Body The code that performs the method39s function is written between the beginning and ending curly braces In the method body a method can declare variables call other methods d rogram structures ifelse statements while loops for loops switch statements and doAnhile loops snumERN anzcumn 395quot snrs uulvERsiTv The return Statement he return type of a method indicates the type ofvalue that the method sends back to h calling location A method that does not return a value has a VOld return type A return statement speci es the value that will be returned return expresslon Its expression must conform to the return type WE snumsau rnmzcnmc 51an univzwsirv Parameters amp Scope Because variables are only visible within the scope in which they are declared no one else can equott em This is a od thing for protectionencapsulation But we need a way of moving data within our program 7 Making everything global i5 a bad idea eThere are time ed to pass on some data to the method for it to Work on that da a mu SnuTHERN PnLv rEcHNIc 5mg ulvliilERSiii39 Para meters When a method is called the actualparameters in the invocation are copied into the formal parameters i he method y amt Hamil chat 0316 um um Int mm stung quot2553th mm xesult um um aha massage enemusmi quotmm xesull 5m snumsm murmur sws UNiVERSiTi Parameters A method is de ned by its Name Return type PARAMETERS the Stuff in the parenthesis When we call a method we need to pass the correct number and type of parameters Speak the languagequot ofthe method WW snumERN anscum sms ulliVERSiTY Constructors Special methods that are called when an object is instantiated using the ne rd A class can have several constructors The job of the class constructors is to initialize the instance vanables ofthe new ob39ec 5m suumsau anzcumn smz IJIIiVERSih Construc or So far we39ve seen attributes and methods 0 a a e 7 Automatically called when class is instantiated 7 Useful rm Setting attributes amp initializing the instance 7 No return type noteven void 7 be public Default constructor is used unless you specify a constmctor For each attribute in the class assign something to it in the constructor initialize mu soumsau museum 5mg UHiiERSiTY mme swim it magma 2n 139pr false lensel lale inmuii mu snumsau rnmzcumc 51an uNiansrrv 5m snuTHEaN PDLVTECHNIE sws wivznsirr Multiple Constructors overloading Constructors are used to initialize our objects We can use parameters to the constructor to customize the initialization Sometimes we have more or less data to use in the customization We d like to be able to pass in only what we know Overloading Overloading involves using the same method Jnction name Vary the number of parameters Vary the type of parameters Cannot just change return type ambiguity In rnvoc Useful to keep things simple Squaring a number U SnuTHERN PnLv rEcHNIr 5mg umvEnsr Overloading Example 1m m in n xelm 1 a 17 am We mm H r xelm 1 a 1 sum mm mm r mm x e summers3r 1m y e smear W 5mm mm 51an univERslTv Constructor Overloading mm m n Wuhan mm mm Nance mm methnd name differmt human my mm mam mm n1ij W m lt mm mam m m n m t was s Place cammnn 33 quotY39 itializztinn in a separate functinn gt gt 5m suumsau anscumn smz urilvERslh mu soumsau museum 5mg imiszle Which is Called BMVLZ4 myCar new BMVLZM BMVLZ4 yourCar new BMW7Z42007 BMW7Z4 herCar new BMW7Z420087 The constructor with the matching parameter de nition will be called If no parameters the 0 constructor If one parameter the int constructor Defining a Constructor yn ax pub Classwanel parameter hsr r lt constructor body gt Note no return value not even void Each constructor must have a different number of parameters or parameters of Default constructor a constructor that takes no arguments Sm sourNERN Pomscumc 5an umvERsm W E E 5 lle2hli quotquot Constructor Examples public class Card Class Scope Instance variables have class scope Any constructor or method of a class can directly refer to instance variables Methods also have class s specmc cunslruclur public Card ml lnllValue string lmlSull l Any method or constructor of a class call any other method of a class without using an object reference 5950 soundan anscumc 5m uulvinsm w snurusm PDLVTECHNIE snrs MINERle Local Scope Summary of Scope A method39s parameters have local scope A method in a class can acce mean39quot at the instance variables of its class a method can directly access its par meters any parameters sent to the method 7 a methods parameters cannot be accessed by my mama any variable the method declares from the method can de ne local variables which poim of Claim quotmquot me end onr39e also have local scope meaningt t39 quot399th or n quot199quotquot onhe 0c Iquot which the variable Is declared whichever 7 a methu c its ecal variables r e a methud s lecal variables cannot be accessed by comes other methods Irst any methods in the class mu snurHERN PanscHNIc 51sz umvERsm mu 2 5 lle392l y c quot39g ACPBSSOF MethOdS Accessor Methods Clients cannot directly access private instance variables so classes p rovide public accessor methods with this standard form Example the accessor method for modefrom the Auto clas puhllc returnType getInstanceVarlahle public stung getModeU l return lustancevarlahlE return Type is return model the same data type as the In stance variable This is the same as the get property Spsu SDUTHERN POLVTECHNIC STATE UNIVERSHV Mutator Methods Allow client to change the values of instance variables public veid setInstanceVarlable dataType newValue validate newValue tnen asslgn to instance variable i This is the same as the set property SM SDUTHERN PDLVTECHNIE t STATE uNivEnsiT39v Common Error Trap Do not declare method parameters Parameters are de ned already and are assigned the values sent by the client to the method Do not give the parameter the same name as the instance variable The parameter has name precedence so it quothidesquot the instance variable Do not declare a local variable with the same name as the instance variable Local variables have name precedence and hide he instance variable is SOUTHERN PoLv rEcHNic STATE uNivERsirI Using this in a Mutator Method public veid setlnstancevarlable dataType lustancevarlableName i this lnstanceVarlableName instancevariab leName Example public veid setModel string model i thismodel model i thismodel refers to the instance variable model refers to the parameter SM SOUTHERN PDLVTECHNIC STATE UNivERsiTv Software Engineering Tip Write the validation code for the instance variable in the mutator method and have the constructor call the mutator method to validate and set initial values This eliminates duplicate code and makes the program easier to maintain gum SOUTHERN POLYTECHNIC 39 STATE UNIVERSlW The Object Reference this How does a method know which object39s data to use this is an implicit parameter sent to methods and is an object reference to the object for which the ethod was called When a method refers to an instance variable name this is implied Thus variabIeName model is understood to be is understood to be this variabIeName this model 3m SOUTHERN PULVTECHNIC STATE UNIVERSlTV Another Example Suppose we wanted a new object to represent a day of the year What data should we store What operations are available What should be public What should be private W 5mm mmm W 5mm Forum 5mg umvERsm 5mg UNNERsm Work Example Here static Variables Also called class variables One copy of a static variable is created per class ampamp as nlt out 2 54m mE am my 9 m 9 m u u o 2 EL m a E m o E m 2 as Iic To de ne a static de the keyword static in its de nition Syntax access pecliler scat dacaType varlahle ane P 939 are o en declared pub variable inclu Exam Puhhi scat nr councAucus u 5m saumsnu anscum sms univERsm static Methods Also called class methods ned to access and change static ble a s static methods cannot access instance variables static methods are associated with the class not with any object static methods can be called before any object is instantiated so it is possible that there will be no instance variables to access 5m sourNERN Pomscumc snurusau PoLvTEcxmln snrs umvERsiT39i 395 5m UHNERSl n39 Overview LeCtUre 6A Iteration 4 kinds of loops Repetition for while do while Briana B lillon39ison 40 each In nite Loops thures 39om Lem ca So aaxe Sniuuanf Autism Wesley saumsau anscum sisi mu awaitezzwxim Looping Iteration In computin we often need to perform the One thing that computers do well is same operations on multiple items repeat commands Typically these tasks follow this pattern Programmers use loops to accomplish e initialize values ttutal m u this 7 pieces items ene at a time add price re total 7 repen results repurttutai 4 kinds of loops in C for loop The ow of control that programmers use to while loo complete jobs with this pattern is called d m r loopingorrepet n ow 399 p foreach loop 5m snumERN Pnu rscumc soumERN Pou rzcuulc 51sz lmlllERSlY39l39 395quot sms uulvERSlTV Criteria for loops Loops in Everyday Life 1Usuay have some initia condition Bad children are told to write sentences on he oard Starting a counter Beginning in a certain state 2Must have a test to continue 3Must make progress towards nishing 39 HaVe 0 write this j r gce Either I will not pour Clorox in the sh tankquot appv 7A5 marry as you can during break SOUTHERN POLYTECHNIO STATE UNlVERSITY The for Loop Ideal when you know the number of iterations to perform before the loop begins Examples Find the sum of 5 numbers Find the maximum of 20 numbers Print the odd numbers from 1 to 10 W vi 7 l Spsu SOUTHERN POLYTEOHNID STATE UNlVERSllV The for loop 39 Good when you know exactly how many times you need to execute something 39 Has format for thializatiorD lttest to continuegt anrenentgtl everything in here is what is repeated over and over again i ln39tialization is where the counter is given a starting value The test determines whether or not to continue The increment can be any amount including negative and occurs allerthe loop statements execute SOUTHERN POLYTECHNIC STATE UNlVERSITV More for Loop Syntax for initialization loop condition loop update loop body Notes semicolons separate terms in the loop header no semicolon follows the loop header curly braces are required only if more than one statement is in the loop body my SOUTHERN POLYTECHNIE STATE UNlVERSITY for Loop Flow of Control 1 The initialization statement is executed once only 2 The loop condition is evaluated lfthe condition is true the loop body is executed 3 The loop update statement is executed and the loop condition is reevaluated 2 And so on until the condition is false SOUTHERN POLYTECHNIC SP5 STATE UNlVERSlTY for Loop Flow of Control iiiii 7 l srsr ltllftlttttlm39 Satisfying the Teacher Example 1000 sentences No problem 1an counter for counter 1 counter lt 1000 counter1 ConsoleWr1teL1ne I W111 not pour Clorox quotl Remember counter is the same as counter counter 1 SW S uYNERN PDLYTECHNIE 39w S UTNERN PDLVTECHNIE 5an umvERsiTv smz LinivERsi n But I want them numbered Why this works No problem mm x m comm 1 can lt mu comma m comm 1 caning lt mu mu Eons m r m wnuhm comm x mn m pm H Consul wmum comm 4 u mn mu you n 5m snumERM anmmn 3m snumsau pnmzcumc smz univEHsm 5an univERsm Why this works Why this works r m cum in Wm M comm 1 can lt mu comma m comm 1 caning lt mu cnuntgx smug wnuhm comm x mn m pm H Consul wnmm 4mm x mn mu pm i Output 1 i Wiii hutpuur Ciuruxin the Fish Tank 5m snumERN PnLv rEcHNI 3m snumERN Pnurrzcumc 51sz umvERsm sms univERsm Why this works Why this works 112 m cum in com lt a 4mm 1 cmmu lt nnn ammuui in 4mm 1 caning lt nnn countzx smug wnuhm comm x m pm H Consul wnmm comm x mn mu you n snurNERN Pomscumc snurNERN PnLvTEcxmln 5 snrs umvsnsm 395 5m uuiyznsm39 Why this works Why this works nan mnehm comm i you H p u H mm hunter m comm 1 can lt mu comma m comm 1 counter lt mu canker n mn m Consul wmum comm v mn m n Output 2 i will nutpuurCluruX in the Fish Tank 5m snumERM anmmn 3m snumsau pnmzcumc 5m univEnsm snrs mivERsiTY Why this works Why this works t T m comm m Wm M comm z 1 can lt mu comma m comm 1 mu lt mu canker smug mnehm comm x Mn N pm r Consul wnmm 4mm x mn mu pm i Output 3 i will nutpuur Ciuruxin the Fish Tank 5m mmm mm 7 W mmm mm 51sz umvERsm sms univERsm Why this works When will it end com We see that this will go on for a while It s a little more interesting later around 1000 m mm m comm 1 can lt mu commui smug mnehm comm x mn w your H 5m snurNERN PDLYTECHNIE 5an umvERsiTv 3950 Why this works smz LinivERsi n counter re Why this works snumsau PnLvTEcxmln m m comm Eons counter 1 countgx lt mu comma in team 1 caning lt mu comm E wnuhm comm t mn m pm H Consul wmum comm u mn m you n Output 899 i Wiii hutpuur Ciurux in the Fish Tank 5950 snumERM anmmn smz unwshsm W t r g 5 ive 2hquot7 cquotquotquot Why this works Why this works lt EEDEEEIJLTZZZC nun comm true rut iast time m c m in team 1 caning lt mu cnuntgx x x mn m pm H n E w Elam canILA x mn m pm A sum snumERN PnLv rEcHNI 51sz umvERsm Why are We finiShEd7 Sim itiwmmcgszwmm this works J m Wm M comm Why this works u lt mu comm mm wnuhm comm m 1 m pm H in cum in canILA 1 caning lt mu comm c Output iEIEIEI i Wiii nut puurCiuruX in the Fish Tank um wnmm comm x mn mt you n snumERN PnuTEcHNIn snurNERN mesmmc 5 5w umvz sm W50 smz uuwzksm Why this works Final Output mm 1 wm not pourCtorok m the sh tank 2 WM not pour Ctorok tn the sh tank 3 WM not pour Ctorok tn the sh tank 4 mm not pourCtorok m the sh tank fatse mm m comm z 1 smug mm mm lt mu caning y Mn N y 1 am am in E m cm H x u you w x and comquot 999 t WM notpour CtOt OX tn the sh tank 1000 tWtH not pourCtorOX tn the sh tank 3m snumERM Pnu rEcHNI W snumERN pomzcumc 5m unw sm sms umvERsm Another Example of Repetl on int num for num numlt num C0Wlnnum Potato snumERN pnmzcum snumERN pnmscumc 51 3quot my umvERsm WW 5an ummsm num lt 3 quotumH CDWnnumquotPotatoquot CDWquotquotumP m OUTPUT WW snuTNERN pomscumc swz umvswsm OUTPUT 3ch SnuTHERN pnmzcum sms unwEPsm int num fornum1 CDWnnumquotPotatoquot OUTPUT m snumERN pnmscumc 4 51m umviwsnr int mm for num CDWnnumquotPotatoquot OUTPUT 3M snumsan pomscumc smz uuwsnsm CDWnnumquotPotatoquot OUTPUT soumsau m W1 5an unwist OUTPUT N SOUTHERN pamzcumc smz umvzzsm CDWnnumquotPotato OUTPUT snuYNERN Pmmmic snumERN PnuTEcHNln EMU 3950 sTArE univERsm smz UulvERsm int mm for num CDWnnumquotPotatoquot 3m snumERM Pnu rEcHNl W snumERN pomzcumc 5mg unwsnsm sms wilvERsm int num int num fornum fornum1 CDWnnumquotPotatoquot coWlnnunquotPotato UTUT n the loop control condition is evaluated and has value false theloop is saidto be satis ed and control passes to the statem ent following the For statem ent 5m Snul NERN Pnu rscum WW snumERN Pnu rzcuul 5mg mnvERsm t 5an unliszle The output was int count for count 4 count gt 0 countquot 1 Potato 2Potato coWIncount 3Potato C0Wln Donequot OUTPUT SMquot SOUTHERN PDLYTECHNIE STATE UlllVEllStlY The white Loop 39 The while loop is designed for repeating a set of operations on data items when we don39t know how many data items there will be r We will get some signal when we have reached the end of the items to process 39 The end of data items could be indicated bya special input value called a sentinel value or by reaching the end of a le 39 Receiving the signal is an event we call this eventcontrolled looping 7 SOUTHERN PDLYTECHNID STATE UNlVETlSlTl39 The while loop 39 Good torwhen you don t know how many times to repeat 39 Teacher says Write until l m happy 39 Has format while ltboolean valuegt stuff to repeat over and over my SOUTHERN PDLYTECHNIE T STATE Ulll lEllSlTl sususovmaaupourocvwc l STATE UNlVEKSlTY Loop Characteristics All loops have the following three characteristics 39 initialization 39 test 39 update SOUTHERN PlTLYTECllNIE STATE UNlVETlSlTY Operation of the white Loop 39 If the condition evaluates to true the loop body is executed then the condition is reevaluated 39 As long as the condition evaluates to true we continue to repeat the loop body 39 The loop body must quotupdate the loop conditionquot that is it must perform some operation that eventually will cause the loop condition to evaluate to false 39 Typically the loop update will be an attempt to read the next input value in order to detect the sentinel value or the end of the le my SOUTHERN POLYTECllNIE sure uwvrrrsnr Countcontrolled Loop int count count 4 initialize loop variable while oountgt 0 res expression l C0Wlnoount repeaedaoion count update loop variable i C0Wln Donequot Sm snumsau PDLYTECHNIC 5mg uuwshsm count while count gt o cOWIncount count C0WnquotDonequot WW S UTNERN PDLVTECHNIE 7 smz unlvzasm Countcontrolled Loop while count 0 cOWIncount OUTPUT count C0WnquotDonequot 5m saumsnu PDLYTEEHNIE 5m UHWEPsm w snurusm PDLVTECHNIE 5mg lmlvERsm Coun controed Loop count int count OUTPUT cOWIncount count C0WnquotDonequot mu snumERN PDLVYECHMIE 51m umvsnsm int count while count gt o OUTPUT cOWIncount cOWIn Donequot Countcontrolled Loop int count quotquot count 4 while count 0 OUTPUT C0WnquotDonequot 3m snumsan anzcuul sms umvERslTv Countcontrolled Loop int count OUTPUT cOWIncount count C0WnquotDonequot Sm snumsau Pommmlc 5mg uliwsnsm mu snumsau PDLVTECHNIE smz UHNERsm39 Countcontrolled Loop id Loop count count while count 0 OUTPUT Qawmmum OUTPUT A 9 count a CDWnquotDonequot C0Wn Done 0 5m saumsnu PDLYTEEHNIE 5m unwEPsln WW ampEquot ivs392ii395 cquotquotquot Countcontrolled Loop t count quotquot d Loop int c u t quotquot Countcontrolle o n count count while count 0 OUTPUT OUTPUT C0Wlncount 4 3 count C0WlnquotDonequot CDWnquotDonequot snumERN pnmscum souTNERN PoLvTEcuull 593quot ems mllvERsm SDSU sms uulvERslTv Countcontrolled Loo int count quotquot count 4 while count gt o OUTPUT OUTPUT CDWncount coWIncount y 9 count C0WnquotD nequot coWInquotDonequot39 5m snumsau Pomscumc snumsau pnmscumn 5mg umvmm 395 5m unwansm Countcontrolled Loop Countcontrolled Loop 39 cum quotquot int count quotquot count 4 while count 0 OUTPUT Qawmmum OUTPUT 4 J a a 2 3 W 4 coWIn Done 3 coWIn Done 3 saumsau anscmm snurHERN PnLvTEcHMIc 59 sms uuwsasm 393quot 5mg uleRsm39 controed Loop count Count Countcontrolled Loop int count39 0 n int c u t quotquot count 4 count A oUTPUT oUTPUT C0Wlncount CDWncoum 3 5 count 2 coun 2 C0WlnquotDonequot awe while count 0 mu snumERN pnmzcumc snumsan anzcumn 5mg umvERsm 395quot sms umvsnsm Example Re Writing 11000 Example ReWriting 11000 0 te Usmg a mee uup ter Usmg a mee map r 4 ml mumquot ml cnunlex mun 1mmquot lt mum quotmu 1mmquot lt 1 m c c an nmnnmnmm man 1 mn nut quoty nusnlejhllngne 1mmquot I mu ml quoty 5m snurNERN Pomscumc sms umvsnsm 3W snurNERN pnmscamn smz UHlvERsl n Example ReWriting 11000 xample ReWriting 11000 uslng awhlle lump counter uslng awhlle lump counter mt cnunlex z 1 mt cnunlex z 1 quotm1 lcnunlex lt 1mm quotn11 lcnuntn lt 1mm a cmmmnmm lcnuntn I quot11 nut quotl lt cnmummgme mth I quot11 mt quotl Output l l Wlll nut puur Clurux m the flsh tank 595 snumERM ansmm 5m unwEHsm 3m snumsau pnmzcumc snrs MINERle uslng awhlle lump Example ReWriting 11000 uslng a we lump Example ReWriting 11000 mt cunnlex 1m cnunlex quot111 lcnunlex lt 1mm quotn11 lcnunlex lt 1mm c nsnlzjhllgL 1 Comte 1 quot111 mt quott Cnnsn mun Comte 1 quot111 mt quott gt Output l l Wlll nut puur Clurux m the flle tanx snumERN Pnu rscumc snumERN Pnu rzcumc 5Wquot 51sz mnvERsm sum sms umvsnsm Example ReWriting 11000 Example ReWriting 11000 uslng a Whlle lump counter uslng a Whlle lump counter mt cunnlex z 1 1m cnunlex z 1 m1 towquot lt mu t quotn11 towquot lt mun lt cnnsnnmntgunz tamquot I quot11 m m on mulejhllngne lcnunlex 1 quot111 mt quott 5m sourNERN Pomscumc 5an unwasz 3W sourNERN PoLvTEcxmln smz UHlvERsm Example ReWriting 11000 nfinite Loops uslng awnlle lump ter mt cuntquot This loop isn39t making a lot of progress Loops that repeal forever are called in nite man Comte lt want t c Apparently lock upquot nmnnwntv Outpul39 nu 1mmquot 1 mn mt quott 1 lvvlll nutpuur Clurux 1n neflsn tan Output 1 lWlllnutpuurCluruxlntneflsntank 1 l Wlll nut puur Clurux 1n the sh tank 595 soumERM anmmn 5m unwEHsm 3m snumsau pnmzcumc snrs MINERle Problem Solved Problem Solved mt mumquot mt Comte z 1 mm 1mmquot lt mnnt t quotmu 1mmquot lt 1mm CnnsnlzjhllgL m Comte 1 mn mt quott cnmnumn me 1mmquot 1 will mt quot1 cmlnle gt 5m snurHERN pnmscumc 51sz umvERsm 3m soumERN anzcumn t sms umvsnsm Problem Solved Problem Solved mt mumquot mt Comte z 1 mm 1mmquot lt in at t quotmu 1mmquot lt 1 nt CnnsnlzjhllgLnlz tommu 1 mn mt quott cnmnumn me 1mmquot 1 mn mt quott u Wt can ex 1 t 2 as Output 1 lWlllnutpuurCluruXlntneflsntank cmquot miquot 5m snurNERN PDLYTECHNIE 5an umvERslTv uslng awhlle lot 3050 quot5 l 2l quotquot Example ReWriting 11000 p ter ml Comte Problem Solved m mquot z 1 m1 rmquot lt mu oannm m rmquot lt m M Mammalquot mquot I quotm m m mum mum gt 1n lcnunlex I will ml quotl 5m saumsm anscum smz unlvEHsm 3m snumsau pnmzcumc 5an MINERle Problem Solved ml Comte Problem Solved ml cnunlex 1 1mmquot lt quotD cnmnnJm m lammu 1 mn nnl quotl cnmlex gt quotml lcnunlex lt nn l Consul a mum me Comte I mu nut n mmler Output 2 l Wlll nutpuur Clurux m we flle tank 5m snumERN PnLv rEcHNI 51sz umvznsm 3m snumERN Pnurrzcumc sms umvsnsm How does it end ml Comte counter How does it end an ml Comte coumer Cnnsnlzjhll m lt v lt Cnnsnlejhl Lme lcnunlex 1 mn ml quotl cmlnlexw gt m lammu 1 mn nnl quotl SW S uYNERN PDLYTECHNIE 3W snumsau PnLvTEcxmln 5an umvERsm smz UHNERsm39 How does it end Problem Solved counter m mmquot s Counter mm mm lt 1 m cnmnumn cnmle 39 gt ml cunnlex mm mm lt mum nn Consul quotnunquot man 1 mn nut quoty Lme mm I will ml quoty cnmlex gt Output 899 Wm nutpuurC uruxm tne sn tank 5m snumERM anmmn snurHERN PnLv rEcHMIc smz unwsasm 393quot snrs unwERsm39 How does it end How does it end ml Comte ml cnunlex z 1 mm mm lt mum quotml 1mmquot lt mum cnmnnJm gun mm 1 mn nut quoty Cnnsnlejhllngne 1mmquot I mu nut n a cnmlex cnmlem gt gt 5m snumERN PnLv rEcHNI 3m snumERN Pnurrzcumc 51sz umvERsm sms umvsnsm How does it end ml cnunlex coumer ml cnunlex coumer 4 um Comte lt nn b 4 mule cmmlex lt 1n onmwnmm mmquot quotm quoty Walkman mmquot quotm m quoty gt 5 n quotHex 11ml u ll mm 1 nu m1 pun Clnxnx m u nsmank SW S uYNERN PDLVTECHNIE 39w S UTNERN PDLVTECHNIE 5an unwsnsm smz UHlvERsl n Example The dowhile loop Z JEZKE Z 39 5quot Similarto while loop Must execute at least one time test is at bottom 21 Has format do 1 mm mnmgmmn c cm H unmannpr while ltboolean valuegt7 W snumsm mmmm W snumERN mummc sure WWW snrs unwsnsm Example Example cuuntfmm 1 m a cuuntfmm l m a counter counter m mum 0 m mum 0 4 aunt r Dunn CnnsnlewriteLine caunter CnnsnlewriteLine caunter while caunter lt a while caunter lt a m snumERN meme 7 W 5quan Pnu rzcumc 51m umvERsm snrsumvsnsm Example Example cuuntfmm 1 m a cuuntfmm l m a counter but mum o m mum 0 an an a amen mnmw CnnsnlewriteLinE cauntEl 439 CnnsnlewriteLinE cauntel while caunter lt 3 while caunter lt 3 Oulput 1 snurNERN PDLYTECHNIE snumsau PnLvTEcxmln 5W snrs umvERslT39l 395 5m unlvERsm xample xamp e cuuntfmm l D a cuuntfmm l m a m mum 0 m mum mm M a mm M CnnsnlewriteLinE cauntEl CnnsnlewriteLinE cauntel while caunter lt 3 while caunter lt 3 5m snumERM anscum 3m snumsau pnmzcumc smz unwEHsm 5an MINERle Example Example cuuntfrumltu a cuuntfmm l m a int caunter 0 int caunter enur nun CnnsnlewriteLine caunter CnnsnlewriteLine caunter while caunter lt a while caunter lt a Oulput 2 5m snumERN PnLv rEcHNI 3m snumERN Pnurrzcumc 51sz umvznsm sms umvsnsm Example Example cuuntfrumltu a cuuntfmm l m a int caunter 0 int caunter dn d caunter 4 cuunter CnnsnlewriteLine caunter CnnsnlewriteLine cuunter while caunter lt 3 while caunter lt 3 39 lute count 5 na 3 hm in sun have 0MP 3 ll tn Hush nut me lung 7 it an my snurNERN PoLvTEcuNIc snui NERN PoLvTEctmin W 5mg UNlVERSlT l saw smz lllIlVERSl n xample The foreach loop cuuntfrurn i tn 3 Often we have a collection of data We39d like to do something to each one ofthe items in the collection Certainly we can do this with a for loop But Cit provides a new loop foreach 7 References an item in the eelleetlen int counter o eeuneer while counter lt a El it e Lunpsthruugh all elements in the eelleetlen new raise so limp l5 nished 5m saumsau PDLYTEEHNII snurHERN PnLirrEcHMic sms unweesm 393quot snrs MINERle foreach template A sample application may lltmxgt mm 1 amuxc39rmu t um Tn e mm in mm mm snurHERN Pnu rscimic snumERN PnLv rEcuNIc 5Wquot ems unlvERsm 3m sms uulvsnslrv foreach example foreach vs for loop Assuming we had a listbox control called The previous foreach loop on the listBoxNames with strings in it collection using a for loop emu my Hum u mum um nun 1n 1 lt mum nee em w 5mm mm emmuneu e um heme smlmumm 139 wee Displays all ofthe strings in capitalization to the user in MessageBoxes Sm soumERN PDLVTECHNIE s39ms ImeRsm Summary for loops good for when you know how many times y eat ou want to rep while and dowhile good for when you don39t foreach loop useful for processing collections All loops must nish or they become in nite loo s All loops must have a test to continue or they become in nite loops


Buy Material

Are you sure you want to buy this material for

25 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

Why people love StudySoup

Jim McGreen Ohio University

"Knowing I can count on the Elite Notetaker in my class allows me to focus on what the professor is saying instead of just scribbling notes the whole time and falling behind."

Kyle Maynard Purdue

"When you're taking detailed notes and trying to help everyone else out in the class, it really helps you learn and understand the I made $280 on my first study guide!"

Steve Martinelli UC Los Angeles

"There's no way I would have passed my Organic Chemistry class this semester without the notes and study guides I got from StudySoup."

Parker Thompson 500 Startups

"It's a great way for students to improve their educational experience and it seemed like a product that everybody wants, so all the people participating are winning."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.