Example: air traffic controller

Arrays in C/C++

Osethatwewantaprogramthatcanreadinalisto fnumb ersandsortthatlist,or econcreteab outit,supp osewehave15numb erstoreadinfroma ers,butthenhowcouldweusealo optocomparethevariablestoeachother? ,sothatwecouldwritesomethinglikemax = 0;for ( i = 0; i < 15 ; i++ ) {if ( number_i > max )max = number_i ;} ++strings:ifwedeclarestring str;thenwecanwritealo oplikefor ( int i = 0; i < (); i++ )cout < < str[i] < < - ;inwhicheachindividualcharacterinstrisaccessedusingthesubscriptop erator[]. ,indexedbysubscripts,allofthesametyp ,itwouldlo oklikethis:number: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Eachelementcouldb eaccessedusingthesubscriptop erator,asinnumber[1]ornumber[7],andwecouldwritealo oplikemax = 0;for ( i = 0; i < 15 ; i++ ) {if ( number_i > max)}

code needs to count how many aluesv are written into the arra,y and stop if it exceeds the array size, or if it runs out of data rst. The while loop has two conditions to check in this case: int list [100]; int temp; length = 0; cin >> temp; // try to read to force eof to become true if the file is empty while ( length < 100 && ! cin . eof )

Tags:

  Arar

Information

Domain:

Source:

Link to this page:

Please notify us if you found a problem with this document:

Other abuse

Advertisement

Transcription of Arrays in C/C++

1 Osethatwewantaprogramthatcanreadinalisto fnumb ersandsortthatlist,or econcreteab outit,supp osewehave15numb erstoreadinfroma ers,butthenhowcouldweusealo optocomparethevariablestoeachother? ,sothatwecouldwritesomethinglikemax = 0;for ( i = 0; i < 15 ; i++ ) {if ( number_i > max )max = number_i ;} ++strings:ifwedeclarestring str;thenwecanwritealo oplikefor ( int i = 0; i < (); i++ )cout < < str[i] < < - ;inwhicheachindividualcharacterinstrisaccessedusingthesubscriptop erator[]. ,indexedbysubscripts,allofthesametyp ,itwouldlo oklikethis:number: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Eachelementcouldb eaccessedusingthesubscriptop erator,asinnumber[1]ornumber[7],andwecouldwritealo oplikemax = 0;for ( i = 0; i < 15 ; i++ ) {if ( number_i > max )max = number[i].}

2 }Thiswouldmakeitp ossibletomanipulatelargecollectionsofhom ogeneousdata,meaningdataofthesametyp e, ossibleinCandC++andallmo (one-Dimensional)ArraySyntax:elementtype arrayname [ size_expression ]where elementtypeisanytyp ethatalreadyexists arraynameisthenameofthearray size_expressionisthenumb erofelementsinthearrayThisdeclaresanarra ynamedarraynamewhoseelementswillb eoftyp eelementtype, fname[24]; // an array named fname with 24 charsint grade[35]; // an array named grade with 35 intsint pixel[1024*768]; // an array named pixel with 1024*768 intsconst int MAX_STUDENTS = 100;double average[MAX_STUDENTS]; // an array named average with 100 doublesstring fruit[5].

3 // an array of 5 C++ stringsTheelementtyp rstexampleisanarraywithbasetyp echar, anarrayofchar. Thingstorememb erab outarrays: Thestartingindexofanarrayis0,not1. Thelastindexisonelessthanthesizeofthearr ay. Ifthearrayhassizeelements, Arrayscontaindataofasingletyp e. Anarrayisasequenceofconsecutiveelementsi nmemoryandthestartofthearrayistheaddress ofits rstelement. Becausethestartingaddressofthearrayinmem oryistheaddressofits rstelement,andallelementsarethesamesizea ndtyp e,thecompilercancalculatethelo ,andeachelementis4byteslong,theelementsa reataddressesB,B+ 4,B+ 8,B+ 12,andsoon,andingeneral,elementarray[k]i sataddressB+ 12k. AlthoughCandC++allowthesizeexpressiontob evariable,youshouldnotuseavariable,forre asonshavingtodowithconceptsofdynamicallo cationandthelifetimeofvariables.

4 Useconstantssuchasmacrode nitionsorconst einitializedatdeclarationtimeintwodi arrayname[size expr] = { list with <= sizeexpr vals };elementtype arrayname[ ] = { list with any number of values };Examples#define MAXSCORES 200#define NUMFRUIT 5const int SIZE = 100;double numbers[SIZE]; // not initializedstring fruit[NUMFRUIT] = {"apple","pear","peach","lemon","mango"} ;int power[ ] = {0,1,2,4,9,16,25,36,49,64,81,100};int counts[SIZE] = {0};int score[MAXSCORES] = {1,1,1}.

5 The rstdeclarationdeclaresbutdo vestrings:applepearpeachlemonmango01234 Thethirdinitializesanarraynamedpower,who sesizeisdeterminedbythenumb erofvaluesinthelistislessthanthesize, ,allelementswillb esetto0,andinthelast,the rstthreearesetto1andtherest, Ifthearraysizeisgiveninbrackets, ,therestofthearrayisinitializedto0's. Ifthesizeisnotgiveninbrackets,thenthesiz eisequaltothenumb erofelementsintheinitializerlist. Ifthereisnoinitializerlist, ,maintain,andreadtheco :arrayname[integer-valued-expression-wit hin-range] < < fruit[0] ; // prints applecout < < powers[1] < < < < powers[2] ; // prints 1 2fruit[3] = apricot.

6 // replaces peach by apricot in fruit[3]counts[SIZE-10] = counts[SIZE-11] + 2; // sets counts[90] to counts[89] + 2 = 2cout < < score[power[4]]; // power[4] = 9, so this outputs scores[9]Noticeinthelasttwoexamplesthattheindexexpressioncanb earbitraryinteger-valuedexpressions, opsandArraysWithoutlo , ,alo opcanb eusedtoinitializeanarray,tomo difyallelements,toaccessallelements, einitializedwithvaluesfromaninputstreamusingafor-lo opguaranteesthatthearrayisnot over lled b /r e a dv a l u e si n t oa r r a yf r o ms t a n d a r di n p u tf o r(i=0 ;i<MAXSCORES ;i ++)c i n>>s c o r e[i].

7 / /L e tm i n s c o r eb et h efirste l e m e n ta sas t a r t i n gg u e s si n tm i n s c o r e=s c o r e[0];/ /C o m p a r er e m a i n i n ga r r a ya l e m e n t st oc u r r e n tm a x s c o r ef o r(i=1 ;i<MAXSCORES ;i ++){if(m i n s c o r e>s c o r e[i])/ /ifc u r r e n te l e m e n t<m i n s c o r em i n s c o r e=s c o r e[i];/ /m a k eitn e wm i n s c o r e/ /A tt h i sp o i n t,m a x s c o r e>=s c o r e[j],f o rallj=0,1,2,..i}c o u t<<T h eminimums c o r eis<<m i n s c o r e<<e n d l;Inthisexample,thescorearrayis lledfromvaluesenteredonthestandardinputs tream, een lled,avariablenamedminscoreissettotheval ueofscore[0].

8 Thenasecondlo opexamineseachelementofscorefromscore[1] ,toscore[2],andsoonuptoscore[MAXSCORE-1] .Ifanelementissmallerthanminscore, op, ,badthingscanhapp eab ortedbytheop :int score[10];for ( int i = 0; i < 20; i++ )cin > > score[i]; ,score[i]isamemoryaddressoutsideofthesco rearray(sinceitis0-basedandthelastindexi s9)andtheprogramwillb eab edeclaredtohavesomanyelements,thatdo esnotknowhowmuchdataitwillreadinfroma leorexternalsource, ,onlypartofthearrayhasb een opthatispro cessingthearraytriestopro cessallarrayelements, lledandthenumb erofdataitemsisnotknowninadvance,thenthe co deneedstocounthowmanyvaluesarewrittenint othearray,andstopifitexceedsthearraysize ,orifitrunsoutofdata ophastwoconditionstocheckinthiscase:i n tlist[100];i n tt e m p;l e n g t h=0 ;c i n>>t e m p.

9 / /t r yt or e a dt of o r c ee o f( )t ob e c o m et r u eift h efileise m p t yw h i l e(l e n g t h<1 0 0&&!c i o f( )){list[l e n g t h]=t e m p;/ /t e m ph a sav a l u e,s oc o p yiti n t ot h elistl e n g t h ++;/ /i n c r e m e n tb e c a u s ewec o p i e dav a l u ei n t olistc i n>>t e m p;/ /r e a dan e wv a l u e;m i g h tm a k ee o f( )t r u e}Thevariablelengthkeepsacountofwhathasb eenputintothearrayandwhenthelo opends,itisguaranteedtob opendsb ecauselengthb ecame100orb ,thearrayhasb een ,allfuturepro dewould ndtheminimumelementoflist:f o r(i=1 ;i<l e n g t h;i ++){if(m i n>list[i])m i n=list[i];}ArraysinFunctionsSupp osethatyouwanttowriteafunctionthatcan ndtheminimumintegerinanarrayofintegers?W ecansafelyansweryestothisquestion,whethe ritisCorC++.

10 :result_type function_name ( .., elementtypearrayname [ ],.. ) ;Forexample,int max( int array[] );void foo( int a[], int b[], double c[]); ,youjustputthetyp ondingargumentwillb eanarrayofthattyp esthefunctionknowhowmanyelementsareinthe array?Itdo esn' know ematchesthebasetyp ,ifwewanttowriteafunctionthat ndstheminimuminanintegerarray,thefunctio nprototyp ewouldb eint min( int array[], int size ); score[MAXSCORES];for ( i = 0; i < MAXSCORES; i++ )cin > > score[i];cout < < The minimum score is < < min(score, MAXSCORES);Noticethatthescorearrayispass edtothemin() ()functionde nitionwouldb ei n tm i n (i n ta r r a y[],i n tsize){i n tm i n v a l u e=a r r a y[0].}


Related search queries