Você está na página 1de 13

5/8/2016

9.1TwoDimensionalArrays


Previous:9.1TwoDimensionalArrays
Up:9.1TwoDimensionalArrays
Next:9.2ImplementingMultiDimensionalArrays
PreviousPage:9.1TwoDimensionalArrays
NextPage:9.2ImplementingMultiDimensionalArrays

9.1TwoDimensionalArrays
Ourfirsttaskistoconsideranumberofexamsforaclassofstudents.Thescoreforeachexamisto
beweighteddifferentlytocomputethefinalscoreandgrade.Forexample,thefirstexammay
contribute30%ofthefinalscore,thesecondmaycontribute30%,andthethirdcontribute40%.We
mustcomputeaweightedaverageofthescoresforeachstudent.Thesumoftheweightsforallthe
examsmustaddupto1,i.e.100%.Hereisourtask:
WTDAVG:Readtheexamscoresfromafileforseveralexamsforaclassofstudents.Readthe
percentweightforeachoftheexams.Computetheweightedaveragescoreforeachstudent.Also,
computetheaveragesofthescoresforeachexamandfortheweightedaveragescores.
Wecanthinkoftheexamscoresandtheweightedaveragescoreforasinglestudentasadatarecord
andandrepresentitasarowofinformation.Thedatarecordsforanumberofstudents,then,isatable
ofsuchrows.Hereisourconceptualviewofthiscollectionofdata:

Letusassumethatallscoreswillbestoredasintegerseventheweightedaverages,whichwillbe
computedasfloat,willberoundedoffandstoredasintegers.Tostorethisinformationinadata
structure,wecanstoreeachstudent'sdatarecord,arowcontainingthreeexamscoresandthe
weightedaveragescore,inaonedimensionalarrayofintegers.Theentiretable,then,isanarrayof
theseonedimensionalarraysi.e.atwodimensionalarray.Withthisdatastructure,wecanaccessa
recordforanindividualstudentbyaccessingthecorrespondingrow.Wecanalsoaccessthescorefor
oneoftheexamsorfortheweightedaverageforallstudentsbyaccessingeachcolumn.Theonly
restrictiontousingthisdatastructureisthatallitemsinanarraymustbeofthesamedatatype.Ifthe
studentidisaninteger,wecanevenincludeacolumnfortheidnumbers.
Supposeweneedtorepresentidnumbers,scoresin3exams,andweightedaverageofscoresfor10
studentsweneedanarrayoftendatarecords,oneforeachstudent.Eachdatarecordmustbeanarray
offiveelements,oneforeachexamscore,onefortheweightedaveragescore,andoneforthestudent
idnumber.Then,weneedanarray,scores[10]thathastenelementseachelementofthisarrayis,
itself,anarrayof5integerelements.Hereisthedeclarationofanarrayofintegerarrays:
scores[10][5]
Thefirstrangesaysthearrayhastenelements:scores[0],scores[1], scores[9].Thesecond
rangesaysthateachofthesetenarraysisanarrayoffiveelements.Forexample,scores[0]hasfive
elements:scores[0][0],scores[0][1],
http://ee.hawaii.edu/~tep/EE160/Book/chap9/section2.1.1.html

scores[0][4].Similarly,anyotherelementmaybe
1/13

5/8/2016

9.1TwoDimensionalArrays

referencedbyspecifyingtwoappropriateindices,scores[i][j].Thefirstarrayindexreferencesthe
onedimensionalarray,scores[i]thesecondarrayindexreferencesthe elementintheone
dimensionalarray,scores[i][j].
Atwodimensionalarraylendsitselftoavisualdisplayinrowsandcolumns.Thefirstindex
representsarow,andthesecondindexrepresentsacolumn.Avisualdisplayofthearray,scores[10]
[5],isshowninFigure9.1.Therearetenrows,(09),andfivecolumns(04).Anelementisaccessed
byrowandcolumnindex.Forexample,scores[2][3]referencesanintegerelementatrowindex2
andcolumnindex3.

Wewillseeinthenextsectionthat,aswithonedimensionalarrays,elementsofatwodimensional
arraymaybeaccessedindirectlyusingpointers.There,wewillseetheconnectionbetweentwo
dimensionalarraysandpointers.Fornow,wewillusearrayindexingasdescribedaboveand
rememberthatarraysarealwaysaccessedindirectly.Also,justaswithonedimensionalarrays,a2D
arraynamecanbeusedinfunctioncalls,andthecalledfunctionaccessesthearrayindirectly.
Wecannoweasilysetdownthealgorithmforourtask:
readthenumberofexamsintono_of_exams
getweightsforeachoftheexams
readexamscoresandidnumberforeachstudent
intoatwodimensionalarray
foreachstudent,computeweightedaverageofscoresintheexams
computeaveragescoreforeachoftheexamsand
fortheweightedaverage
printresults

Wecaneasilywritethetoplevelprogramdriverusingfunctionstodotheworkofreadingscores,
gettingtheweights,computingtheweightedaverages,printingscores,averagingeachsetofscores,
andprintingtheaverages.ThedriverisshowninFigure9.2.

http://ee.hawaii.edu/~tep/EE160/Book/chap9/section2.1.1.html

2/13

5/8/2016

9.1TwoDimensionalArrays

Wehavedeclaredanarray,scores[][],withMAXrowsandCOLScolumns,wherethesemacrovalues
arelargeenoughtoaccommodatetheexpecteddata.Wehaveusedseveralfunctions,whichwewill
soonwriteandincludeinthesameprogramfile.Theirprototypesaswellasthoseofotherfunctions
aredeclaredattheheadofthefile.Inthedriver,getwts()readstheweightsfortheexamsintoan
array,wts[],returningthenumberofexams.Thefunction,read_scores(),readsthedatarecordsinto
thetwodimensionalarray,scores[][],andreturnsthenumberofdatarecords.Thefunction,
wtd_avg(),computestheweightedaveragesofallexamscores,andavg_scores()computesan
averageofeachexamscorecolumnaswellasthatoftheweightedaveragecolumn.Finally,
print_scores()andprint_avgs()printtheresultsincludingtheinputdata,theweightedaverages,
andtheaveragesoftheexams.
http://ee.hawaii.edu/~tep/EE160/Book/chap9/section2.1.1.html

3/13

5/8/2016

9.1TwoDimensionalArrays

Letusfirstwritegetwts().ItmerelyreadstheweightforeachoftheexamsasshowninFigure9.3.

Thefunctionpromptstheuserforthenumberofexamscores,andreadsthecorrespondingnumberof
floatvaluesintothewts[]array.Noticethattheloopindex,ibeginswiththevalue1.Thisisbecause
theelementwts[0],correspondingtothestudentidcolumn,doesnothaveaweightandshouldbe
ignored.Aftertheweightshavebeenread,weflushthekeyboardbufferofanyremainingwhitespace
sothatanykindofdata(includingcharacterdata)canbereadfromtheinput.Thefunctionreturns
thenumberofexams,n.
Wewillassumethatthedataforthestudentscoresisstoredinafileintheformatofonelineper
student,witheachlinecontainingthestudentidfollowedbytheexamscores.Toreadthisdataintoa
twodimensionalarray,wemustfirstopentheinputfile.Thisisdonebythefunctionopenfile()
showninFigure9.4,whichpromptsforthefilenameandtriestoopenthefile.Ifthefileopens
successfully,thefilepointerisreturned.Otherwise,thefunctionprintsamessageandaskstheuserto
retypethefilename.Theusermayquitatanytimebytypinganewlineorendoffile.Ifanendoffile
istypedorthetypedstringisempty,theprogramisterminated.Oncetheinputfileisopened,weread
dataitemsintothearray,fillingintheelementsonerow(student)atatime.Weusetwoindex
variables,rowandcol,varyingtherowtoaccesseachrowinturnand,withineachrow,wevarycol
toaccesselementsofeachcolumninturn.Wewillneedadoublynestedlooptoreadthedatainthis
manner.Thefunctionisgiventhenumberofstudents,thevariablestds,andthenumberofexams,
nexs.Wewillusecolumn0tostorethestudentidnumbersandthenextnexscolumnstostorethe
scores.Thus,ineachrow,wereadnexs+1datavaluesintothearray.Thisisdonebythefunction,
read_scores(),alsoshowninFigure9.4.

http://ee.hawaii.edu/~tep/EE160/Book/chap9/section2.1.1.html

4/13

5/8/2016

9.1TwoDimensionalArrays

Theinputfileisfirstopenedusingopenfile(),andthedatarecordsarereadintothearraycalled
http://ee.hawaii.edu/~tep/EE160/Book/chap9/section2.1.1.html

5/13

5/8/2016

9.1TwoDimensionalArrays

ex[][]withinthefunction.ThefunctionreturnsthenumberofrecordsreadeitherwhenEOFisreached
orwhenthearrayisfilled.Eachintegerdataitemisreadfromafile,fp,intoatemporaryvariable,n.
Thisvalueisthenassignedtotheappropriateelement,ex[row][col].Whenalldatahasbeenread,

theinputfileisclosedandthenumberofrecordsreadisreturned.
Noticeinmain()inFigure9.2,wepassthe2Darraytoread_scores()justaswedidforone
dimensionalarrays,passingthearrayname.Asweshallseeinthenextsection,thearraynameisa
pointerthatallowsindirectaccesstothearrayelements.Thetwodimensionalarrayasasargument
mustbedeclaredinthefunctiondefinitionasaformalparameter.InFigure9.4,wehavedeclaredit
asex[][COL]withtwosetsofsquarebracketstoindicatethatitpointstoatwodimensionalarray.In
ourdeclaration,wemustincludethenumberofcolumnsinthearraybecausethisspecifiesthesizeof
eachrow.Recall,thetwodimensionalarrayisanarrayofrows.Oncethecompilerknowsthesizeof
arowinthearray,itisabletocorrectlydeterminethebeginningofeachrow.
Thenextfunctioncalledinmain()computestheweightedaverageforeachrow.Theweightedaverage
foronerecordisjustthesumofeachoftheexamscoretimestheactualweightofthatexam.Ifthe
scoresareinthearray,ex[][],thenthefollowingcodewillcomputeaweightedaverageforasingle
row,row:
wtdavg=0.0;
for(col=1;col<=nexs;col++)
wtdavg+=ex[row][col]*wts[col]/100.0;

Weconvertthepercentweighttotheactualweightmultiplybythescore,andaccumulateitinthesum,
wtdavgyieldingafloatvalue.Thewtdavgwillbestoredintheintegerarray,ex[][],afterroundingto
anearestinteger.Ifwesimplycastwtdavgtoaninteger,itwillbetruncated.Toroundtothenearest
integer,weadd0.5towtdavgandthencastittointeger:
ex[row][nexs+1]=(int)(0.5+wtdavg);

Theweightedaverageisstoredintothecolumnofthearrayafterthelastexamscore.Theentire
functionisshowninFigure9.5

http://ee.hawaii.edu/~tep/EE160/Book/chap9/section2.1.1.html

6/13

5/8/2016

9.1TwoDimensionalArrays

Computingaverageofeachoftheexamsandtheweightedaverageissimple.Wejustsumeachofthe
columnsanddividebythenumberofitemsinthecolumn,andisalsoshowninFigure9.5.Foreach
examandfortheweightedaveragecolumn,thescoresareaddedanddividedbylim,thenumberof
rowsinthearray,usingfloatingpointcomputation.Theresultisroundedtothenearestintegerand
storedinthearray,avg[].Figure9.6showsthefinaltwofunctionsforprintingtheresults.

http://ee.hawaii.edu/~tep/EE160/Book/chap9/section2.1.1.html

7/13

5/8/2016

9.1TwoDimensionalArrays

Runningtheprogramwithdatafile,wtdin.datasfollows:
37076
529280
539556
544852
559895
5710095
6110065
629576
638665
7010090
717373
759479

producesthefollowingsamplesession:
***WeightedAverageofScores***
Numberofexams:2
PercentWeightforExam1:50
http://ee.hawaii.edu/~tep/EE160/Book/chap9/section2.1.1.html

8/13

5/8/2016

9.1TwoDimensionalArrays

PercentWeightforExam2:50
InputFile,RETURNtoquit:wtdin.dat

AverageforExam1=88
AverageforExam2=75
Averageoftheweightedaverage=82
Inthisprogram,wehaveassumedthattheinputfilecontainsonlythedatatoberead,
i.e.thestudentidnumbersandexamscores.Ourread_scores()functioniswrittenwith
thisassumption.However,theinputfilemightalsocontainsomeheadinginformationsuch
asthecoursenameandcolumnheadingsinthefirstfewlinesofthefile.Wecaneasily
modifyread_scores()todiscardthefirstfewlinesofheadings.
Asasecondexampleofapplicationoftwodimensionalarrays,considerourpreviouspayroll
example.Inthiscase,thedataitemsinapaydatarecordarenotallofthesamedata
type.Theidnumbersareintegers,whereasalltheotheritemsarefloat.Therefore,we
mustuseanarrayofintegerstostoretheidnumbers,andatwodimensionalfloatarrayto
storetherestofthedatarecord.Thealgorithmisnodifferentfromtheprogramwe
developedinChapter
thatcomputedpay.Thedifferenceisthatnowweuseatwo
dimensionalarrayforallfloatpayrolldatainsteadofseveralonedimensionalarrays.The
idnumbersarestillstoredinaseparateonedimensionalarray.Sincethedatastructures
arenowdifferent,wemustrecodethefunctionstoperformthetasksofgettingdata,
calculatingpay,andprintingresults,butstillusingthesamealgorithms.

http://ee.hawaii.edu/~tep/EE160/Book/chap9/section2.1.1.html

9/13

5/8/2016

9.1TwoDimensionalArrays

TheprogramdriverandtheheaderfilesareshowninFigure9.7.Theprogramdeclaresan
integerarrayforidnumbersandatwodimensionalfloatarrayfortherestofthedata
record.Thesuccessivecolumnsinthetwodimensionalarraystorethehoursworked,rateof
pay,regularpay,overtimepay,andtotalpay,respectively.Wehavedefinedmacrosfor
symbolicnamesfortheseindexvalues.Asinthepreviousversion,theprogramgetsdata,
calculatespay,andprintsdata.Thedifferenceisinthedatastructuresused.Functions
toperformtheactualtasksareshowninFigure9.8and9.9andincludedinthesame
programsourcefile.

http://ee.hawaii.edu/~tep/EE160/Book/chap9/section2.1.1.html

10/13

5/8/2016

http://ee.hawaii.edu/~tep/EE160/Book/chap9/section2.1.1.html

9.1TwoDimensionalArrays

11/13

5/8/2016

9.1TwoDimensionalArrays

Eachfunctionusesatwodimensionalarray,payrec[][].Therowindexspecifiesthedata
recordforasingleid,andthecolumnindexspecifiesadataitemintherecord.Thedata
recordalsocontainsthetotalpay.Asampleinteractionwiththeprogram,pay2rec.c,is
shownbelow.
SampleSession:
***PayrollProgramRecordsin2Darrays***
http://ee.hawaii.edu/~tep/EE160/Book/chap9/section2.1.1.html

12/13

5/8/2016

9.1TwoDimensionalArrays

ID<zerotoquit>:5
HoursWorked:30
RateofPay:10
ID<zerotoquit>:10
HoursWorked:50
RateofPay:12
ID<zerotoquit>:0
***PAYROLL:FINALREPORT***


Previous:9.1TwoDimensionalArrays
Up:9.1TwoDimensionalArrays
Next:9.2ImplementingMultiDimensionalArrays
PreviousPage:9.1TwoDimensionalArrays
NextPage:9.2ImplementingMultiDimensionalArrays
tep@wiliki.eng.hawaii.edu
WedAug1709:20:12HST1994

http://ee.hawaii.edu/~tep/EE160/Book/chap9/section2.1.1.html

13/13

Você também pode gostar