Arrays CS180 15Feb2008 Announcements Exam1GradesonBlackboard - - PowerPoint PPT Presentation

arrays
SMART_READER_LITE
LIVE PREVIEW

Arrays CS180 15Feb2008 Announcements Exam1GradesonBlackboard - - PowerPoint PPT Presentation

Arrays CS180 15Feb2008 Announcements Exam1GradesonBlackboard Project2scores:endofClass Project4,duedate:20 th Feb Snakes&LaddersGame


slide-1
SLIDE 1

Arrays

CS180 15Feb2008

slide-2
SLIDE 2

Announcements

  • Exam1GradesonBlackboard
  • Project2scores:endofClass
  • Project4,duedate:20th Feb

– Snakes&LaddersGame

  • ReviewofQ5,Q8,Q11&Programming

Questions

slide-3
SLIDE 3

Arrays:Whattheymean?

  • Anarray isanobjectusedtostorea

(possiblylarge)collectionofdata.

  • Allthedatastoredinthearraymustbeof

thesametype.

  • Itenablesyoutouseasinglenameto

representacollectionofitems&referto anitembyspecifyingtheitemnumber

slide-4
SLIDE 4

TypesofArrays

  • One-DimensionalArrays

– int students[5]

  • Multi-Dimensionalarrays

– Simplestformisa2-DArray

  • int students[3][5]

– Exampleof3-DArray

  • int students[5][7][3]
slide-5
SLIDE 5

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;

slide-6
SLIDE 6

Diagram:CreationofArray

Statement int number[]; number=newint[2];

  • Thisisanarrayof

length2

  • “number” isareference

thatpointstothefirst memoryaddress Result

number pointsnowhere number number[0] number[1]

Memorylocations

slide-7
SLIDE 7
  • 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.

slide-8
SLIDE 8

ArrayTerminology

slide-9
SLIDE 9

Arrayindexoutofbounds

  • Itisaruntimeerrorwhichiscausedby

incorrectuseofarrayindex.

– Ex:int number[]=newint[2]; – number[0]=1; – number[1]=2; – number[2]=17;

Error:array“number” hasjust2elements!

slide-10
SLIDE 10

InitializingArrays

  • Anarraycanbeinitializedatthetimeitis

declared.

  • example

double[]reading={3,3,15.8,9.7};

–Thesizeofthearrayisdeterminedby thenumberofvaluesintheinitializer list.

slide-11
SLIDE 11

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; }

slide-12
SLIDE 12

ArraysinClasses&Methods

  • Arrayscanbeusedasinstancevariables

inclasses.

  • Bothanindexedvariableofanarrayand

anentirearraycanbeaargumentofa method.

  • Methodscanreturnanindexedvariableof

anarrayoranentirearray.

slide-13
SLIDE 13

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

slide-14
SLIDE 14

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.

slide-15
SLIDE 15

Useof=&==withArrays

– Theassignmentoperatorcreatesanalias, not acopyofthearray. – Theequalityoperatordeterminesiftwo referencescontainthesamememory address,not iftwoarrayscontainthesame values.

slide-16
SLIDE 16

MakingaCopyofanArray

  • example

int[]a=newint[50]; int[]b=newint[50]; ... for(int j=0;j<a.length;j++) b[j]=a[j];

slide-17
SLIDE 17

Determiningthe“Equality” ofTwo Arrays

  • Todetermineiftwoarraysatdifferent

memorylocationscontainthesame elementsinthesameorder,definean

equals methodwhichdeterminesif

–botharrayshavethesamenumberof elements –eachelementinthefirstarrayisthe sameasthecorrespondingelementin thesecondarray.

slide-18
SLIDE 18

SwappingArrayelements

  • classinterchange
slide-19
SLIDE 19

UsesofArrays

  • Searchinganelementinalistofelements
  • Sorting

– Ascendingorder – Descendingorder – Alphabeticorder

slide-20
SLIDE 20

Example:SelectionSort

  • Selectionsortbegins

byfindingthe smallestiteminthe arrayandswappingit withtheitemina[0].

slide-21
SLIDE 21

SelectionSort:class

classSelectionSort

slide-22
SLIDE 22

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’

slide-23
SLIDE 23

2-DimensionalArray

2-Drepresentation double[][]Salary=newdouble[10][6]; Department10,Employee1: Salary[9][0] Salaryinformation

  • f10departments

eachhaving6 employees

slide-24
SLIDE 24

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

slide-25
SLIDE 25

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

slide-26
SLIDE 26

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]); } } }

slide-27
SLIDE 27

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

slide-28
SLIDE 28

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

slide-29
SLIDE 29

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

slide-30
SLIDE 30

Review:Exam1– Program1

(20points)Writeaprogramthatpromptsforanumbernwhichindicatesthenumberof columnsandusesthenumbertodisplaythefollowingpattern(depictingn=6where themaximumnumberof Xisn. X XX XXX XXXX XXXXX XXXXXX XXXXX XXXX XXX XX X

slide-31
SLIDE 31

Review:Exam1– Program2

Writeaprogramthatconvertsauser-definedintegerntobasekwherekisanother userdefinedinteger.Yourprogramshouldfirstpromptfortheintegernwhichwillbe converted,thenpromptforthebasevaluek. Yourprogramshouldalsowritetheresultasastringinthefollowingformat: n=resultbasek

slide-32
SLIDE 32

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()