版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Chapter5Arrays数组Outlines5.1OneDimensionalArrays一维数组5.2MultidimensionalArrays多维数组2ScalarVariablesversusAggregateVariablesSofar,theonlyvariableswe’veseenarescalar:capableofholdingasingledataitem.Calsosupportsaggregatevariables,whichcanstorecollectionsofvalues.TherearetwokindsofaggregatesinC:
arraysstructures35.1One-DimensionalArrays一维数组Arraysletusstoreasetofdata数据可用来存储一组数据Anarrayisadatastructurecontaininganumberofdatavalues,allofwhichhavethesametype.数组包含一组变量,这些变量类型相同Thesevalues,knownaselements,canbeindividuallyselectedbytheirpositionwithinthearray.这些变量叫做数组元素Theelementsofaone-dimensionalarrayaarearrangedoneafteranotherinasinglerow(orcolumn):一维数组所有元素在内存中连续排列,占据连续的内存空间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:可以用宏定义来声明数组长度
#defineN10 … inta[N];65.1One-DimensionalArraysArraySubscriptingHowtoaccessanarrayelement?Theelementsofanarrayoflengthnareindexedfrom0ton–1.Ifaisanarrayoflength10,itselementsaredesignatedbya[0],a[1],…,a[9]:75.1One-DimensionalArraysArraySubscriptingExpressionsoftheforma[i]arelvalues,sotheycanbeusedinthesamewayasordinaryvariables:数组元素可以像普通变量一样用 a[0]=1; printf("%d\n",a[5]); ++a[i];
/*thesubscriptcanbeanyintegerexpression*/85.1One-DimensionalArrays数组惯用循环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下标越界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;数组元素的下标可以用表达式表示135.1One-DimensionalArraysArrayInitialization数组初始化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初值少于数组长度,缺省的默认为0(整型实型数组)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.数组长度缺省,默认其长度等于初值的个数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};有时,用户只想对其中几个数组元素初始化,就用“指定初始化”,其他元素默认为0.175.1One-DimensionalArraysDesignatedInitializers(C99)Designatorsmustbeintegerconstantexpressions.Ifthelengthofthearrayisomitted,adesignatorcanbeanynonnegativeinteger.Thecompilerwilldeducethelengthofthearrayfromthelargestdesignator.数组长度缺省的时候,根据初值的标识符来推导其长度。Thefollowingarraywillhave24elements:
int
b[]
=
{[5]
=
10,
[23]
=
13,
[11]
=
36,
[15]
=
29};Aninitializermayuseboththeolder(element-by-element)techniqueandthenewer(designated)technique:可以同时用老的方法和新的方法来初始化:
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多维数组在内存中实际上是一维数组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]在内存中,二维数组是按行排列的 。
a[0]即先存放a[0]行,再存放a[1]行。
a[1]5.2MultidimensionalArraysNestedforloopsareidealforprocessingmultidimensionalarrays.Considertheproblemofinitializinganarrayforuseasanidentitymatrix.Apairofnestedfor
loopsisperfect:
通常用两重循环(循环嵌套)来处理二维数组
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二维数组初始化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.分隔行的内部大括号可以省略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}};初始化的时候如果只提供部分初值,则其他默认为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. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 便民市场摊贩工作总结
- 幼儿园中班教案《秋风》含反思
- 2024年度贷款购买房产纠纷调解合同3篇
- 内科护理工作总结
- 房地产业员工培训方案
- 建筑行业装修设计经验分享
- 委托清收处置协议
- 2024年度高科技研发项目单方保密协议书3篇
- 托育大班游戏课程设计
- 游泳课程设计原理
- 车辆灭失承诺书
- 唐诗宋词鉴赏(第二版)PPT完整全套教学课件
- 微机保护装置改造施工方案
- 门诊病历书写模板全
- 煤油(火油)的理化性质及危险特性表MSDS
- 锅炉延期检验申请书
- 液压与气压传动中职PPT完整全套教学课件
- 国开大学2023年01月11067《知识产权法》期末考试答案
- 直接打印800字作文纸
- (完整word版)人教版高中数学大纲
- 货物供货总体服务方案
评论
0/150
提交评论