Arrays CS180 15Feb2008 Announcements Exam1GradesonBlackboard - - PowerPoint PPT Presentation
Arrays CS180 15Feb2008 Announcements Exam1GradesonBlackboard - - PowerPoint PPT Presentation
Arrays CS180 15Feb2008 Announcements Exam1GradesonBlackboard Project2scores:endofClass Project4,duedate:20 th Feb Snakes&LaddersGame
Announcements
- Exam1GradesonBlackboard
- Project2scores:endofClass
- Project4,duedate:20th Feb
– Snakes&LaddersGame
- ReviewofQ5,Q8,Q11&Programming
Questions
Arrays:Whattheymean?
- Anarray isanobjectusedtostorea
(possiblylarge)collectionofdata.
- Allthedatastoredinthearraymustbeof
thesametype.
- Itenablesyoutouseasinglenameto
representacollectionofitems&referto anitembyspecifyingtheitemnumber
TypesofArrays
- One-DimensionalArrays
– int students[5]
- Multi-Dimensionalarrays
– Simplestformisa2-DArray
- int students[3][5]
– Exampleof3-DArray
- int students[5][7][3]
CreatinganArray
- Declareanarray– 2forms
– typearrayname[]; Ex:int number[]; – type[]arrayname; Ex:int []number;
- Creatememorylocation
– arrayname=newtype[size]; – Ex:number=newint[2]; – Herewehavecreatedanarrayoftypeintegerwith2 elementsandnameditas number
- Putvalues
– arrayname[index]=value; – Ex:number[0]=35; – Ex:number[1]=40;
Diagram:CreationofArray
Statement int number[]; number=newint[2];
- Thisisanarrayof
length2
- “number” isareference
thatpointstothefirst memoryaddress Result
number pointsnowhere number number[0] number[1]
Memorylocations
- Index/SubscriptofArray
– int number[i] – Here“i” isanintegerusedtorefertoanelement
- fthearraynumber.ItiscalledtheIndex
- Ex:number[0]:indicatesthefirstelementofnumber
- Ex:number[1]:indicatesthesecondelementof
number
- Length:InstanceVariable
- length isapublicinstancevariable
- Thelengthvariablestoresthenumberofelementsthe
arraycanhold.
- UsingArray_Name.length typicallyproducesclearercode
thanusinganintegerliteral.
ArrayTerminology
Arrayindexoutofbounds
- Itisaruntimeerrorwhichiscausedby
incorrectuseofarrayindex.
– Ex:int number[]=newint[2]; – number[0]=1; – number[1]=2; – number[2]=17;
Error:array“number” hasjust2elements!
InitializingArrays
- Anarraycanbeinitializedatthetimeitis
declared.
- example
double[]reading={3,3,15.8,9.7};
–Thesizeofthearrayisdeterminedby thenumberofvaluesintheinitializer list.
InitializingArrays,cont.
- Uninitialized arrayelementsaresettothe
defaultvalueofthebasetype.
- However,it’sbettertouseeitheran
initializer listorafor loop.
int[]count=newint[100]; for(int i=0,i<count.length,i++) { count[i]=0; }
ArraysinClasses&Methods
- Arrayscanbeusedasinstancevariables
inclasses.
- Bothanindexedvariableofanarrayand
anentirearraycanbeaargumentofa method.
- Methodscanreturnanindexedvariableof
anarrayoranentirearray.
ArraysinClasses&Methods Example
classcs180Class { StringstudentName[],firstName[]; publiccs180Class() { System.out.println("enter numberofstudents:"); int num_students=keyboard.nextInt(); firstName =newString[num_students]; ... studentName =setData(firstName); } String[]setData (Stringname[]) { String[]temp=newString[name.length]; for(int i=0;i<name.length;i++) { temp[i]=name[i]; } returntemp; } }
Arrayasinstancevariables Arrayasargumentofamethod: CallbyValue ReturninganArray
WhataboutMain method?
- Recalltheheadingformethodmain:
publicstaticvoidmain(String[]args) AnarrayofString valuescanbeprovidedinthecommand line. example
javaTestProgram MaryLou – args[0] issetto “Mary” – args[1] issetto “Lou” System.out.println(“Hello “ +args[0]+ “ “ +args[1]);
prints HelloMaryLou.
Useof=&==withArrays
– Theassignmentoperatorcreatesanalias, not acopyofthearray. – Theequalityoperatordeterminesiftwo referencescontainthesamememory address,not iftwoarrayscontainthesame values.
MakingaCopyofanArray
- example
int[]a=newint[50]; int[]b=newint[50]; ... for(int j=0;j<a.length;j++) b[j]=a[j];
Determiningthe“Equality” ofTwo Arrays
- Todetermineiftwoarraysatdifferent
memorylocationscontainthesame elementsinthesameorder,definean
equals methodwhichdeterminesif
–botharrayshavethesamenumberof elements –eachelementinthefirstarrayisthe sameasthecorrespondingelementin thesecondarray.
SwappingArrayelements
- classinterchange
UsesofArrays
- Searchinganelementinalistofelements
- Sorting
– Ascendingorder – Descendingorder – Alphabeticorder
Example:SelectionSort
- Selectionsortbegins
byfindingthe smallestiteminthe arrayandswappingit withtheitemina[0].
SelectionSort:class
classSelectionSort
Multi-DimensionalArrays
- 2-DimensionalArray
– Arow&Columnstructure – int [][]world=newint[10][9] – Indexingcanbedoneusing2integers:i,j
- world[i][j]:referstoelementatrowiandcolumnj
- Length:2-Darray
– world.length:returnsthe#ofrows – world[i].length:returnsthe#ofcolumnsin row‘i’
2-DimensionalArray
2-Drepresentation double[][]Salary=newdouble[10][6]; Department10,Employee1: Salary[9][0] Salaryinformation
- f10departments
eachhaving6 employees
Initialize2-DArrays
- Youcaninitializebynestingofloops
finalint MAX_ROW=25; finalint MAX_COL=1000; double[][]experData =newdouble[MAX_ROW][MAX_COL]; int i,j; for(i=0;i<MAX_ROW;i++) {
for(j=0;j<MAX_COL;j++) { experData [i][j]=0.0; }
}
- Alternateway:
– double[][]scores={ {5.3,6.9,8.8,1.7}, {2.2,9.4,1.6,7.5} };
2rows,4columns
RaggedArrays
- Sinceatwo-dimensionalarrayinJavaisan
arrayofarrays,eachrowcanhaveadifferent numberofelements(columns).
- Arraysinwhichrowshavedifferentnumbersof
elementsarecalledraggedarrays.
- Example
int[][]b=newint[3][]; b[0]=newint[5];//arrayof5elements b[1]=newint[7];//arrayof7elements b[2]=newint[4];//arrayof4elements
Quiz
- Task:printallthesystem.out.println statements.
publicclassarrayTest { publicstaticvoidmain(String[]args){ String[]names={"Hemant","David","Wini","Kaku"}; System.out.println("length ofthearray:"+names.length); for(int i=0;i<names.length;i++) { System.out.println(names[i]); } } }
Review:Exam1– Q5
Q5.Giventhefollowingcode: doublea=1/3; doubleb=1/3; doublec=1/3; doublesum=a+b+c; Thevalueofvariablesumis: (a)0.9999 (b)0.0 (c)0.999999999999999999 (d)1.0 Q5.ModifiedVersion .Giventhefollowingcode: doublea=1/3; doubleb=1/3; doublec=1/3; doublesum=a+b+c; Thevalueofvariablesumis: – Allintegers:0 – Allfloats0.0 – Alldoubles:0.0
Review:Exam1– Q8
Whatistheoutputofthefollowingprogramfragment? Strings1="Howareyou?"; Strings2="Whoareyou?"; int compareVal =(s1.substring(3)).compareTo(s2.substring(3))>0?1:0; switch(compareVal) { case1:System.out.println(s1);break; case0:System.out.println(s2); } (a)wareyou? (b)Howareyou? Whoareyou? (c)Whoareyou? (d)Howareyou?
Solution: s1.substring(3)-->areyou? s2.substring(3)-->areyou? s1.substring(3)).compareTo(s2.substring(3)-->0 Whoareyou? beginningindextilltheendofstring
Review:Exam1– Q11
WhichofthefollowingaretrueregardingStringcomparison(assumes1ands2have beendeclared asString)? I.Theoperator"=="andthemethodequalsalwaysreturnthesameresult II.ThecompareTo methodshouldbeusedtocomparetwostringsinsteadofthe
- perators">"and
"<" III.s1.compareTo(s2)returnsanegativenumberifs1comesafters2lexicographically (a)IandIIonly (b)I,IIandIII (c)IIonly (d)IIandIIIonly
Review:Exam1– Program1
(20points)Writeaprogramthatpromptsforanumbernwhichindicatesthenumberof columnsandusesthenumbertodisplaythefollowingpattern(depictingn=6where themaximumnumberof Xisn. X XX XXX XXXX XXXXX XXXXXX XXXXX XXXX XXX XX X
Review:Exam1– Program2
Writeaprogramthatconvertsauser-definedintegerntobasekwherekisanother userdefinedinteger.Yourprogramshouldfirstpromptfortheintegernwhichwillbe converted,thenpromptforthebasevaluek. Yourprogramshouldalsowritetheresultasastringinthefollowingformat: n=resultbasek
Review:Exam1– Program3
Nicomachus’sTheoremstatesthatthenthcubicnumbern3isasumofnconsecutive
- ddumbers.Forexample:
13=1 23=3+5 33=7+9+11 43=13+15+17+19 Thefirsttermineachsequenceisn(n 1)+1. Writecodefor:
- privatevoidinitialize()
- publicint byMultiply()
- publicint byAdd()