programming with arrays intro to pointers · programming with arrays intro to pointers cs 16:...

24
Programming with Arrays Intro to Pointers CS 16: Solving Problems with Computers I Lecture #11 Ziad Matni Dept. of Computer Science, UCSB

Upload: others

Post on 16-Mar-2020

25 views

Category:

Documents


1 download

TRANSCRIPT

ProgrammingwithArraysIntrotoPointersCS16:SolvingProblemswithComputersI

Lecture#11

ZiadMatniDept.ofComputerScience,UCSB

•  Thursday,5/17inthisclassroom•  Startsat2:00PM**SHARP**–  Pleasestartarriving5-10minutesbeforeclass

•  Imayaskyoutochangeseats•  PleasebringyourUCSBIDswithyou

•  Closedbook:nocalculators,nophones,nocomputers•  OnlyallowedONE8.5”x11”sheetofnotes–onesidedonly–  Youhavetoturnitinwithyourexam

•  Youwillwriteyouranswersontheexamsheetitself.5/10/18 Matni,CS16,Sp18 2

What’sontheMidterm#2?EVERYTHINGFromLectures7–12,including…

•  Makefiles

•  DebugTechniques•  NumericalConversions

•  Strings:C++vsC-strings•  StringsandCharacters:MemberFunctions&Manipulators

•  FileI/O•  Arrays•  Pointers5/10/18 Matni,CS16,Sp18 3

LectureOutline

•  ProgrammingwithArrays•  SequentialSearchofArrays•  Multi-DimensionalArrays

•  IntroductiontoC++MemoryMap•  IntroductiontoPointers

5/10/18 Matni,CS16,Sp18 4

SummaryDifference

voidthisFunction(intarr[],intsize);Array“arr”getspassedandwhateverchangesaredoneinsidethefunctionwillresultinchangesto“arr”whereit’scalled.

voidthisFunction(constintarr[],intsize);Array“arr”getspassedBUTwhateverchangesaredoneinsidethefunctionwillNOTresultinchangesto“arr”whereit’scalled.

int*thisFunction(intarr[],intsize);Array“arr”getspassedandwhateverchangesaredoneinsidethefunctionwillresultinchangesto“arr”whereit’scalled.ADDITIONALLY,anewpointertoanarray“thisFunction”ispassedback(DON’TWORRYABOUTTHISUNTILAFTERWELEARNABOUTPOINTERS!)5/10/18 Matni,CS16,Sp18 5

ProgrammingWithArrays

•  Thesizerequirementforanarraymightneedtobeun-fixed–  Sizeisoftennotknownwhentheprogramiswritten

•  Acommonsolutiontothesizeproblem (whilestillusing“regular”arrays):– Declarethearraysizetobethelargestthatcouldbeneeded– Decidehowtodealwithpartiallyfilledarrays

5/10/18 Matni,CS16,Sp18 6

Seedemofile:fillingUpArray.cpp

PartiallyFilledArrays

•  Whenusingarraysthatarepartiallyfilled…– Functionsdealingwiththearraymaynotneedtoknowthe declaredsizeofthearray

– Onlyhowmanymaximumnumberofelementsneedtobestoredinthearray!

•  Aparameter-let’scallitnumber_used-maybesufficienttoensurethatreferencedindexvaluesarelegal

5/10/18 Matni,CS16,Sp18 7

Seedemofile:fillingUpArray.cpp

SearchingArrays•  Asequentialsearchisonewaytosearchanarrayforagivenvalue.The

algorithmisasfollows:1.  Lookateachelementfromfirsttolasttoseeifthetargetvalueisequalto

anyofthearrayelements

2.  Theindexofthetargetvalueisreturnedtoindicatewherethevaluewasfoundinthearray

3.  Avalueof-1isreturnedifthevaluewasnotfoundanywhere

Pros?Cons?

5/10/18 Matni,CS16,Sp18 8

5/10/18 Matni,CS16,Sp18 9

SequentialSearch

Task:Searchthearrayfor“ff”

ARRAYa[]a[0]a[1]a[2]a[3]a[4]a[5]a[6]a[7]a[8]a[9]a[10]a[11]a[12]

Result:inposition9

5/10/18 Matni,CS16,Sp18 10

SimpleSequentialSearchFunctionExample

intSeqSearch(intarr[],intarray_size,inttarget){

intindex(0);boolfound(false);while((!found)&&(index<array_size)){ if(arr[index]==target) found=true; else index++;}if(found) returnindex;else return-1;

}

1.  Lookforatargetvalueinsideofagivenarray

2.  Ifyoufindit,returnitslocation(i.e.index)inthearray

3.  Ifyoudon’tfindit,return-1

Multi-DimensionalArrays•  C++allowsarrayswithmultipleindexdimensions(havetobesametype,tho…)•  EXAMPLE:charpage[30][100];

declaresanarrayofcharactersnamedpage–  pagehastwoindexvalues:The1strangesfrom0to29The2ndrangesfrom0to99

–  Eachindexinenclosedinitsownbrackets

•  Pagecanbevisualizedasanarrayof30rowsand100columns–  pageisactuallyanarrayofsize30–  page'sbasetypeisanarrayof100characters

5/10/18 Matni,CS16,Sp18 12

[0][0] [0][1] … [0][98] [0][99]

[1][0] [1][1] … [1][98] [1][99]

… … … … …

[28][0] [28][1] … [28][98] [28][99]

[29][0] [29][1] … [29][98] [29][99]

Seedemofile:multidimensionalDemo.cpp

ProgramExample:GradingProgram

•  Graderecordsforaclasscanbestoredinatwo-dimensionalarray

•  Aclasswith4studentsand3quizzesthearraycouldbedeclaredas intgrade[4][3];–  Thefirstarrayindexreferstothenumberofastudent–  Thesecondarrayindexreferstoaquiznumber

•  Yourtextbook,Ch.7,Display7.14hasanexample

5/10/18 Matni,CS16,Sp18 13

Eachstudent(0thru3)has3grades(0thru2)

5/10/18 Matni,CS16,Sp18 14

UseNestedfor-loopstoGoThroughaMDA

Example:constintMAX1=10,MAX2=20;intarr[MAX1][MAX2];…for(inti=0;i<MAX1;i++)for(intj=0;j<MAX2;j++) cout<<arr[i][j];

5/10/18 Matni,CS16,Sp18 15

InitializingMDAs

•  Recallthatyoucandothisforuni-dimensionalarraysandgetallelementsinitializedtozero: doublenumbers[100]={0};

•  Formultidimensionalarrays,it’ssimilarsyntax:doublenumbers[5][100]={{0},{0}};

OR:doublenumbers[5][100]={0};

•  Whatwouldthisdo?doublenumbers[2][3]={{6,7},{8,9}};

5/10/18 Matni,CS16,Sp18 16

Seedemofile:multidimensionalDemo.cpp

MultidimensionalArrayParametersinFunctions

•  Recallthatthesizeofanarrayisnotneededwhendeclaringaformalparameter:voiddisplay_line(chara[],intsize);

•  BUTthebasetypemustbecompletelyspecifiedintheparameterdeclarationofamulti-dimensionalarrayvoiddisplay_page(charpage[][100],intsize_dimension1);

Look!Nosize!

Basehasasizedefined!

5/10/18 Matni,CS16,Sp18 17

Sizeishereinstead!

5/10/18 Matni,CS16,Sp18 18

INTROTOPOINTERS

Section9.1inbook

PassingbyValuesWhatdoesthiscodeprintout?

voidswapValue(intx,inty){inttmp=x;x=y;y=tmp;

}intmain(){inta(30),b(40);cout<<a<<""<<b<<endl;swapValue(a,b);cout<<a<<""<<b<<endl;

}5/10/18 Matni,CS16,Sp18 19

IsIt:A.30403040B.30404030C.Somethingelse

Pointers

•  Apointeristhememoryaddressofavariable

•  Whenavariableisusedasacall-by-referenceargument,it’stheactualaddressinmemorythatispassed

5/10/18 Matni,CS16,Sp18 20

MemoryAddresses

•  Considerintvariablenumthatholdstheintvalue42•  numisassignedaplaceinmemory(whatdoesthat??)

•  Inthisexampletheaddressofthatplaceinmemoryis0x001F–  Generally,memoryaddressesusehexadecimals

(andusually8ofthem,notjust4…butthisisONLYanexample…)–  The“0x”atthestartisjusttoindicatethenumberisahexadecimal

5/10/18 Matni,CS16,Sp18 21

Address Data0x001D 00x001E -250x001F 420x0020 13320x0021 -40090x0022 7

1byte

num

MemoryAddresses

•  Theaddressofavariablecanbeobtainedbyputtingtheampersandcharacter(&)beforethevariablename.

•  &iscalledtheaddress-ofoperator

•  Example:intnum_add=&num;willresultinnum_addtoholdthevalue0x001F(or31indecimal)

5/10/18 Matni,CS16,Sp18 22

Address Data0x001D 00x001E -250x001F 420x0020 13320x0021 -40090x0022 7… …

0x98A0 31

1byte

num

num_add

YOURTO-DOs

q TurninLab6onMondayq DoHW11bynextTuesdayq StudyforyourMidterm#2onThursday!

q VisitProf’sandTAs‘officehoursifyouneedhelp!

q Enjoythebeautifuloutdoors

5/10/18 Matni,CS16,Sp18 23

5/10/18 Matni,CS16,Sp18 24