Example: dental hygienist

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] < < - ;inwhicheachindividualcharacterinstrisac cessedusingthesubscriptop erator[].

Suppose that we want a program that can read in a list of numbers and sort that list, or nd the largest avlue in that list. oT be concrete about it, suppose we have 15 numbers to read in from a le and sort into ascending order. We could declare 15 ariablesv to store the numbers, but then how could we use a loop to compare the ariablesv to each ...

Tags:

  Order, Sort, Ascending, Ascending order

Information

Domain:

Source:

Link to this page:

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

Other abuse

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] < < - ;inwhicheachindividualcharacterinstrisac cessedusingthesubscriptop erator[].

2 ,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],andwecou ldwritealo oplikemax = 0;for ( i = 0; i < 15 ; i++ ) {if ( number_i > max )max = number[i] ;}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].

3 // 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].

4 // 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.

5 AlthoughCandC++allowthesizeexpressiontob evariable,youshouldnotuseavariable,forre asonshavingtodowithconceptsofdynamicallo cationandthelifetimeofvariables. 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.

6 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};The rstdeclarationdeclaresbutdo vestrings:applepearpeachlemonmango01234 Thethirdinitializesanarraynamedpower,who sesizeisdeterminedbythenumb erofvaluesinthelistislessthanthesize, ,allelementswillb esetto0,andinthelast,the rstthreearesetto1andtherest, Ifthearraysizeisgiveninbrackets, ,therestofthearrayisinitializedto0's.

7 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.

8 // 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]Noticeinthelasttwoexamplesthatt heindexexpressioncanb earbitraryinteger-valuedexpressions, opsandArraysWithoutlo , ,alo opcanb eusedtoinitializeanarray,tomo difyallelements,toaccessallelements, einitializedwithvaluesfromaninputstreamu singafor-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.)

9 I ++)c i n>>s c o r e[i];/ /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].

10 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;/ /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&&!)


Related search queries