C程序設計基礎 英文版 課件 Chapter 5 Arrays_第1頁
C程序設計基礎 英文版 課件 Chapter 5 Arrays_第2頁
C程序設計基礎 英文版 課件 Chapter 5 Arrays_第3頁
C程序設計基礎 英文版 課件 Chapter 5 Arrays_第4頁
C程序設計基礎 英文版 課件 Chapter 5 Arrays_第5頁
已閱讀5頁,還剩34頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權,請進行舉報或認領

文檔簡介

Chapter5Arrays數(shù)組Outlines5.1OneDimensionalArrays一維數(shù)組5.2MultidimensionalArrays多維數(shù)組2ScalarVariablesversusAggregateVariablesSofar,theonlyvariableswe’veseenarescalar:capableofholdingasingledataitem.Calsosupportsaggregatevariables,whichcanstorecollectionsofvalues.TherearetwokindsofaggregatesinC:

arraysstructures35.1One-DimensionalArrays一維數(shù)組Arraysletusstoreasetofdata數(shù)據(jù)可用來存儲一組數(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:可以用宏定義來聲明數(shù)組長度

#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下標越界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ù)組元素的下標可以用表達式表示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ù)組長度,缺省的默認為0(整型實型數(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ù)組長度缺省,默認其長度等于初值的個數(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ù)組元素初始化,就用“指定初始化”,其他元素默認為0.175.1One-DimensionalArraysDesignatedInitializers(C99)Designatorsmustbeintegerconstantexpressions.Ifthelengthofthearrayisomitted,adesignatorcanbeanynonnegativeinteger.Thecompilerwilldeducethelengthofthearrayfromthelargestdesignator.數(shù)組長度缺省的時候,根據(jù)初值的標識符來推導其長度。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多維數(shù)組在內(nèi)存中實際上是一維數(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)嵌套)來處理二維數(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)部大括號可以省略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. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經(jīng)權益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論