0% found this document useful (0 votes)
43 views13 pages

9 Array

This document discusses representing exam scores for multiple students using a two-dimensional array data structure. It describes reading exam scores and student IDs from a file into a 2D array with rows for each student and columns for the exam scores and student ID. Functions are used to get the exam weights from the user, read the scores from the file into the 2D array, compute weighted averages for each student, and calculate averages for each exam. The overall process and functions like getting weights, reading scores, computing averages, and printing results are demonstrated.

Uploaded by

lunding
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views13 pages

9 Array

This document discusses representing exam scores for multiple students using a two-dimensional array data structure. It describes reading exam scores and student IDs from a file into a 2D array with rows for each student and columns for the exam scores and student ID. Functions are used to get the exam weights from the user, read the scores from the file into the 2D array, compute weighted averages for each student, and calculate averages for each exam. The overall process and functions like getting weights, reading scores, computing averages, and printing results are demonstrated.

Uploaded by

lunding
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 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
[email protected]
WedAug1709:20:12HST1994

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

13/13

You might also like