版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
Chapter5Arrays數(shù)組Outlines5.1OneDimensionalArrays一維數(shù)組5.2MultidimensionalArrays多維數(shù)組2ScalarVariablesversusAggregateVariablesSofar,theonlyvariableswe’veseenarescalar:capableofholdingasingledataitem.Calsosupportsaggregatevariables,whichcanstorecollectionsofvalues.TherearetwokindsofaggregatesinC:
arraysstructures35.1One-DimensionalArrays一維數(shù)組Arraysletusstoreasetofdata數(shù)據(jù)可用來(lái)存儲(chǔ)一組數(shù)據(jù)Anarrayisadatastructurecontaininganumberofdatavalues,allofwhichhavethesametype.數(shù)組包含一組變量,這些變量類型相同Thesevalues,knownaselements,canbeindividuallyselectedbytheirpositionwithinthearray.這些變量叫做數(shù)組元素Theelementsofaone-dimensionalarrayaarearrangedoneafteranotherinasinglerow(orcolumn):一維數(shù)組所有元素在內(nèi)存中連續(xù)排列,占據(jù)連續(xù)的內(nèi)存空間45
int
a
[10];
a[0]a[1]...a[9]ArraynameThenumberofelementsArrayDeclarationThetypeofthearray’selements
Thesevalues,knownaselements,canbeindividuallyselectedbytheirpositionwithinthearray.Position---indexTheelementsofaone-dimensionalarrayaarearrangedoneafteranotherinasinglerow(orcolumn)5.1One-DimensionalArraysArrayVariableDeclarationTodeclareanarray,wemustspecifythetypeofthearray’selementsandthenumberofelements:
inta[10];Thelengthofthearraycanbeany(integer)constantexpression.Usingamacrotodefinethelengthofanarrayisanexcellentpractice:可以用宏定義來(lái)聲明數(shù)組長(zhǎng)度
#defineN10 … inta[N];65.1One-DimensionalArraysArraySubscriptingHowtoaccessanarrayelement?Theelementsofanarrayoflengthnareindexedfrom0ton–1.Ifaisanarrayoflength10,itselementsaredesignatedbya[0],a[1],…,a[9]:75.1One-DimensionalArraysArraySubscriptingExpressionsoftheforma[i]arelvalues,sotheycanbeusedinthesamewayasordinaryvariables:數(shù)組元素可以像普通變量一樣用 a[0]=1; printf("%d\n",a[5]); ++a[i];
/*thesubscriptcanbeanyintegerexpression*/85.1One-DimensionalArrays數(shù)組慣用循環(huán)ArraySubscriptingManyprogramscontainfor
loopswhosejobistoperformsomeoperationoneveryelementinanarray.ExamplesoftypicaloperationsonanarrayaoflengthN:慣用法
IDIOM
for(i=0;i<N;i++) a[i]=0;/*clearsa*/
for(i=0;i<N;i++) scanf("%d",&a[i]);/*readsdataintoa*/
for(i=0;i<N;i++) sum+=a[i];/*sumstheelementsofa*/9Classexercise24:reversethearrayProgram:ReversingaSeriesofNumbers逆序輸出enteraseriesofnumbers,thenwritesthenumbersinreverseorder:
Enter10numbers:34824910279423115031 Inreverseorder:31501123947102498234Theprogramstoresthenumbersinanarrayasthey’reread,thengoesthroughthearraybackwards,printingtheelementsonebyone.10
#include<stdio.h>
#defineN10
intmain(){inta[N],i;
printf("Enter%dnumbers:",N);for(i=0;i<N;i++)scanf("%d",&a[i]);
printf("Inreverseorder:");for(i=N-1;i>=0;i--)printf("%d",a[i]);printf("\n");
return0;}115.1One-DimensionalArraysArraySubscriptingOutofArrayBounds下標(biāo)越界Cdoesn’trequirethatsubscriptboundsbechecked;ifasubscriptgoesoutofrange,theprogram’sbehaviorisundefined.Acommonmistake:forgettingthatanarraywithnelementsisindexedfrom0ton–1,not1ton: inta[10],i;
for(i=1;i<=10;i++) a[i]=5;
Withsomecompilers,thisinnocent-lookingfor
statementcausesaninfiniteloop.125.1One-DimensionalArraysArraySubscriptingAnarraysubscriptmaybeany
integerexpression:
a[i+j*10]=0;Theexpressioncanevenhavesideeffects:
i=0; while(i<N) a[i++]=0;數(shù)組元素的下標(biāo)可以用表達(dá)式表示135.1One-DimensionalArraysArrayInitialization數(shù)組初始化Themostcommonformofarrayinitializerisalistofconstantexpressionsenclosedinbracesandseparatedbycommas:
inta[10]={1,2,3,4,5,6,7,8,9,10};1412345678910a[0]a[1]a[2]a[3]a[4]a[5]a[6]a[7]a[8]a[9]5.1One-DimensionalArraysArrayInitialization初值少于數(shù)組長(zhǎng)度,缺省的默認(rèn)為0(整型實(shí)型數(shù)組)Iftheinitializerisshorterthanthearray,theremainingelementsofthearrayaregiventhevalue0:
intb[10]={1,2,3,4,5,6}; /*initialvalueofais{1,2,3,4,5,6,0,0,0,0}*/Usingthisfeature,wecaneasilyinitializeanarraytoallzeros:
intb[10]={0}; /*initialvalueofais{0,0,0,0,0,0,0,0,0,0}*/
There’sasingle0insidethebraces.155.1One-DimensionalArraysArrayInitializationIt’sillegalforaninitializertobecompletelyempty.It’salsoillegalforaninitializertobelongerthanthearrayitinitializes.Ifaninitializerispresent,thelengthofthearraymaybeomitted:
intb[]={1,2,3,4,5,6,7,8,9,10};Thecompilerusesthelengthoftheinitializertodeterminehowlongthearrayis.數(shù)組長(zhǎng)度缺省,默認(rèn)其長(zhǎng)度等于初值的個(gè)數(shù)165.1One-DimensionalArraysDesignatedInitializers(C99)指定初始化It’softenthecasethatfewelementsofanarrayneedtobeinitializedexplicitly;theotherelementscanbegivendefaultvalues.{0forint,‘\0’forchar}Anexample:
intb[10]= {0,
0,
1,
0,
0,
2,
0,
0,
3,
0};C99’sdesignatedinitializerscanbeusedtosolvethisproblem.Here’showwecouldredothepreviousexampleusingadesignatedinitializer:
inta[15]={[2]=1,[5]=2,[8]=3};有時(shí),用戶只想對(duì)其中幾個(gè)數(shù)組元素初始化,就用“指定初始化”,其他元素默認(rèn)為0.175.1One-DimensionalArraysDesignatedInitializers(C99)Designatorsmustbeintegerconstantexpressions.Ifthelengthofthearrayisomitted,adesignatorcanbeanynonnegativeinteger.Thecompilerwilldeducethelengthofthearrayfromthelargestdesignator.數(shù)組長(zhǎng)度缺省的時(shí)候,根據(jù)初值的標(biāo)識(shí)符來(lái)推導(dǎo)其長(zhǎng)度。Thefollowingarraywillhave24elements:
int
b[]
=
{[5]
=
10,
[23]
=
13,
[11]
=
36,
[15]
=
29};Aninitializermayuseboththeolder(element-by-element)techniqueandthenewer(designated)technique:可以同時(shí)用老的方法和新的方法來(lái)初始化:
inta[10]={9,
3,
2,
[4]
=
6,
1,
9,
[8]
=
8};189320619080a[0]a[1]a[2]a[3]a[4]a[5]a[6]a[7]a[8]a[9]5.1Variable-LengthArrays
inti,length;Scanf(“%d”,&length);//10
inta[length];
for(i=0;i<length;i++) if(i%2==0) a[i]=2; else a[i]=1;192121212121a[0]a[1]a[2]a[3]a[4]a[5]a[6]a[7]a[8]a[9]5.2MultidimensionalArraysAnarraymayhaveanynumberofdimensions.Thefollowingdeclarationcreatesatwo-dimensionalarray(amatrix,inmathematicalterminology):
intm[5][9];m
has5rowsand9columns.Bothrowsandcolumnsareindexedfrom0:20a[0][0]a[0][1]a[0][2]a[0][3]a[1][0]a[1][1]a[1][2]a[1][3]a[2][0]a[2][1]a[2][2]a[2][3]21e.g:inta[3][4];Column0123row0row1row2Toaccesstheelementofa
inrowi,columnj,wemustwritea[i][j].5.2MultidimensionalArraysAlthoughwevisualizetwo-dimensionalarraysastables,that’snotthewaythey’reactuallystoredincomputermemory.Cstoresarraysinrow-majororder,withrow0first,thenrow1,andsoon.Howthem[5][9]arrayisstored:22多維數(shù)組在內(nèi)存中實(shí)際上是一維數(shù)組23
a[0][0]a[0][1]a[0][2]a[1][0]a[1][1]a[1][2]Theexpressionm[i]
designatesrowiofm,andm[i][j]thenselectselementjinthisrow.
a[0]---------a[0][0]a[0][1]a[0][2]a[2][3] a[1]---------a[1][0]a[1][1]a[1][2]在內(nèi)存中,二維數(shù)組是按行排列的 。
a[0]即先存放a[0]行,再存放a[1]行。
a[1]5.2MultidimensionalArraysNestedforloopsareidealforprocessingmultidimensionalarrays.Considertheproblemofinitializinganarrayforuseasanidentitymatrix.Apairofnestedfor
loopsisperfect:
通常用兩重循環(huán)(循環(huán)嵌套)來(lái)處理二維數(shù)組
for(row=0;row<N;row++) for(col=0;col<N;col++)
prinf(“%d”,a[row][col]);for(i=0;i<5;i++) for(j=0;j<5;j++)scanf(“%d”,&a[i][j]);24Variable-Length2DarrayDeclarenEnternDeclarethearrayEntertheelementsOutput25intn;scanf(“%d”,&n);inti,a[n][n];for(i=0;i<n;i++) for(j=0;j<n;j++)
scanf(“%d”,&a[i][j]);for(i=0;i<n;i++)
{for(j=0;j<n;j++)
prinf(“%d”,a[i][j]);
prinf(“\n”);
}Classexercise25:thematrixAsktheusertoinputatwodimensionalarray(NXN),thenoutputthematrix.
DeclarenEnternDeclarethearrayEntertheelements(forloop)Output26for(i=0;i<n;i++) for(j=0;j<n;j++)5.2Arraysdiagonal
introw,col,n;Scanf(“%d”,&n);5
doublea[n][n];
for(row=0;row<n;row++) for(col=0;col<n;col++) if(row==col) a[row][col]=1.0; else a[row][col]=0.0;27a[0][0]a[0][1]a[0][2]a[0][3]a[0][4]a[1][0]a[1][1]a[1][2]a[1][3]a[1][4]a[2][0]a[2][1]a[2][2]a[2][3]a[2][4]a[3][0]a[3][1]a[3][2]a[3][3]a[3][4]a[4][0]a[4][1]a[4][2]a[4][3]a[4][4]Classexercise26:themaindiagonalAsktheusertoinputatwodimensionalarray(NXN),thenoutputthemaindiagonalelements.
DeclarenEnternDeclarethearrayEntertheelements(forloop)Output28a[0][0]a[0][1]a[0][2]a[1][0]a[1][1]a[1][2]a[2][0]a[2][1]a[2][2]Column012row0row1row2for(i=0;i<n;i++) for(j=0;j<n;j++)Classexercise27:thesecondarydiagonalAsktheusertoinputatwodimensionalarray(NXN),thenoutputthesumofthesecondarydiagonalelements.DeclarenEnternDeclarethearrayEntertheelements(forloop)Output29a[0][0]a[0][1]a[0][2]a[1][0]a[1][1]a[1][2]a[2][0]a[2][1]a[2][2]Column012row0row1row2for(i=0;i<n;i++) for(j=0;j<n;j++)5.2MultidimensionalArraysInitializingaMultidimensionalArray二維數(shù)組初始化Wecancreateaninitializerforatwo-dimensionalarraybynestingone-dimensionalinitializers:
intm[5][9]={{1,1,1,1,1,0,1,1,1}, {0,1,0,1,0,1,0,1,0}, {0,1,0,1,1,0,0,1,0}, {1,1,0,1,0,0,0,1,0}, {1,1,0,1,0,0,1,1,1}};3031Wecanevenomittheinnerbraces:Oncethecompilerhasseenenoughvaluestofillonerow,itbeginsfillingthenext.分隔行的內(nèi)部大括號(hào)可以省略inta[3][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12}};Or:inta[3][4]={1,2,3,4,5,6,7,8,9,10,11,12};row0
row1
row
2a[0][0]a[0][1]a[0][2]a[0][3]
a[1][0]a[1][1]a[1][2]a[1][3]
a[2][0]a[2][1]a[2][2]a[2][3]1234567891011125.2MultidimensionalArraysInitializingaMultidimensionalArrayIfaninitializerisn’tlargeenoughtofillamultidimensionalarray,theremainingelementsaregiventhevalue0.Thefollowinginitializerfillsonlythefirstthreerowsofm;thelasttworowswillcontainzeros: intm[5][9]={{1,1,1,1,1,0,1,1,1}, {0,1,0,1,0,1,0,1,0}, {0,1,0,1,1,0,0,1,0}};初始化的時(shí)候如果只提供部分初值,則其他默認(rèn)為0325.2MultidimensionalArraysInitializingaMultidimensionalArrayIfaninnerlistisn’tlongenoughtofillarow,theremainingelementsintherowareinitializedto0:
intm[5][9]={{1,1,1,1,1,0,1,1,1}, {0,1,0,1,0,1,0,1}, {0,1,0,1,1,0,0,1}, {1,1,0,1,0,0,0,1}, {1,1,0,1,0,0,1,1,1}};335.2MultidimensionalArraysInitializingaMultidimensionalArray指定初始化C99’sdesignatedinitia
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 二零二五年度林權(quán)流轉(zhuǎn)與林業(yè)資源保護(hù)合作合同4篇
- 上海市閔行區(qū)24校2025屆中考生物押題卷含解析
- 二零二五版LED顯示屏內(nèi)容管理系統(tǒng)集成合同3篇
- 二零二五版房地產(chǎn)股權(quán)托管與風(fēng)險(xiǎn)控制合同3篇
- 2024陶幻離婚后共同子女課外活動(dòng)費(fèi)用分擔(dān)協(xié)議3篇
- 2025年度瓶裝純凈水生產(chǎn)加工合作協(xié)議4篇
- 2025年度5G通信技術(shù)研究人員聘用協(xié)議書4篇
- 2025年綠植市場(chǎng)綠植銷售與售后服務(wù)合同3篇
- 二零二四年內(nèi)墻抹灰班組高效施工勞務(wù)分包協(xié)議6篇
- 2025年度新能源儲(chǔ)能技術(shù)合作開發(fā)與應(yīng)用合同4篇
- 2025年河北供水有限責(zé)任公司招聘筆試參考題庫(kù)含答案解析
- Unit3 Sports and fitness Discovering Useful Structures 說(shuō)課稿-2024-2025學(xué)年高中英語(yǔ)人教版(2019)必修第一冊(cè)
- 農(nóng)發(fā)行案防知識(shí)培訓(xùn)課件
- 社區(qū)醫(yī)療抗菌藥物分級(jí)管理方案
- NB/T 11536-2024煤礦帶壓開采底板井下注漿加固改造技術(shù)規(guī)范
- 2024年九年級(jí)上德育工作總結(jié)
- 2024年儲(chǔ)罐呼吸閥項(xiàng)目可行性研究報(bào)告
- 除氧器出水溶解氧不合格的原因有哪些
- 沖擊式機(jī)組水輪機(jī)安裝概述與流程
- 新加坡SM2數(shù)學(xué)試題
- 畢業(yè)論文-水利水電工程質(zhì)量管理
評(píng)論
0/150
提交評(píng)論