Example: bachelor of science

C++ Summary notes and exercises - Universidade de Aveiro

C++SummarynotesandexercisesJune4,2012 Thesenotesprovideaguidelineforthepractic alsessionsbasedontheb o ok C++Primer, ,Jos eLa joie, oAddisonWesleyProfessional .Eachchaptershouldb erelevantforthenumericalapplicationswear eusuallyinterestedinphysicswillb eomitted(oronlybrie ycommented).Ineachsectionwewillprovideas ummaryofthemainp eprovidedinazip lewithaREADME leexplainingwhatyouhavetodoandthesourcec o desolutionthatIpro o ok,Iwillalsoextractsomeexamplesandexerci sesfrom C++byDissection ++ cation& esofb ehaviourtob , o okissupp osedto:i)Explainthebasic lesstructureofabasicC++programandexplain howtocompilesimpleprograms;ii)Giveyoua avourofsomeofthebasiclanguage words sothatyoucanwriteverysimpleprograms,anda nideaab outthedatastructurestob ++ de le(that'sjustatext le), (.

C++ Summary notes and exercises June 4, 2012 These notes provide a guideline for the practical sessions based on the book C++ Primer, ourthF Edition By Stanley B. Lippman, Josée Lajoie, Barbara E. Moo Addison Wesley Professional . Each chapter should be read in parallel with the practical session. Some technical parts which are less

Tags:

  Notes, Chapter

Information

Domain:

Source:

Link to this page:

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

Other abuse

Advertisement

Transcription of C++ Summary notes and exercises - Universidade de Aveiro

1 C++SummarynotesandexercisesJune4,2012 Thesenotesprovideaguidelineforthepractic alsessionsbasedontheb o ok C++Primer, ,Jos eLa joie, oAddisonWesleyProfessional .Eachchaptershouldb erelevantforthenumericalapplicationswear eusuallyinterestedinphysicswillb eomitted(oronlybrie ycommented).Ineachsectionwewillprovideas ummaryofthemainp eprovidedinazip lewithaREADME leexplainingwhatyouhavetodoandthesourcec o desolutionthatIpro o ok,Iwillalsoextractsomeexamplesandexerci sesfrom C++byDissection ++ cation& esofb ehaviourtob , o okissupp osedto:i)Explainthebasic lesstructureofabasicC++programandexplain howtocompilesimpleprograms;ii)Giveyoua avourofsomeofthebasiclanguage words sothatyoucanwriteverysimpleprograms,anda nideaab outthedatastructurestob ++ de le(that'sjustatext le), (.

2 CppmeansC++source le).Inthat main(){..return 0;}Everythingelseyourprogramdo esmustb o dyofthefunctionisinsidetheblo ckdelimitedbythebraces{}.Thedotsdenoteyo ursourceco ebytheint(the rstline)andithasnoarguments(fornow). ; . ,inC++,thelaststatementisassumedifomitte d,sostrictlysp eaking,itdo esnothavetob ,gotothedirectorywhereyour lehasb eensavedandcompileitbyinvoking$ g++ -o ,g++isthecompilerwhichusesthesource ject le(the-o,isa agwhichmeansob ject le) (./meanscurrentdirectory thismayb esystemdep endent)$ . (b )usuallyyouhavetohitCtrl+ esystemdep ++languagedo ,inadditiontothelanguage, :TheStandardLibrarycanb ethoughtofasasetoffunctionsanddatatyp esthatareco dedinC++somewhereinlibrary esinthelibrarybyincludingtherelevant lesinyoursourceco le:#include<iostream>int main(){.}

3 Whenyoucompileyourco de,therelevantiostream leswillthenb elo (inputoutput)are: Input:Thisisdonethroughthecinob jectwhichusuallyapp earsintheco ::isthescop eop jectsinthestandardlibrary,toavoidclashes withvariablesde e#include<iostream>int main(){std::cin >> var1 >> var2 >> ..>> varN;..where>>istheinputop eratorwhichreadsfromthestandardinput(usu allywhattheusertyp esintheterminal,oratext leifweredirecttheinput wewillseehowtodoso)intothevariablesvar1, var2,.., reads fromtheinput, :Sometimesyoumaywanttosendan end-of- le signalwhenenteringinput, esystemdep endent,butusuallyforUNIX itisCtrl+dandforWindowsCtrl+z.}

4 Output:Similarlytotheinputstreamthereare 3di erentoutputstreams,whichordinarilyareall streamedintotheterminal,butcanb estreamedtodata ::cout,std:: 'purp osetooutputdata,loginformationab outtherunoftheprogramfortheuseranderrori nformationfortheuserresp eillustratedwithstd::cout:#include<iostream>int main(){std::cout << espression1 << expression2 << ..<< expresionN << std::endl;..whereeachexpressionwillb erator,nowwehavetheoutputop erator<< , 'se ectistoprintoutthestreamimediatelyforthe usertosee(it ushedthestream).}

5 Ifnotpresentitmayb edelayedandprintedlater!Itisimp ortanttousethiswhendebuggingco detokeeptrackexactlywhereatthep ereaddirectlyfromaninput le(input )byexecutingyourprogramas$ . < <meansredirectionoftheinputtob ereadbythe leinfront, ,itwillthenb eautomaticallyreadfromthetext ,onecanredirecttheoutputstreamsto ::coutweusethe> ::cerrandstd::clogoneuses2>andb othareredirectedtothesame le,soforexample$ . > 2> ::couttoout ::cerrandstd::clogtoinfo :Hint:Youneedtoincludetheheaderforthemat hfacilitiesofthestandardlibrary#include<cmath>sothatthelog(x) dearecommentedbyplacingadoubleslashatthe b eginingoftheline// This is a commented line4 Forblo cksoflinesonecanuse/* This is a commented block of * ducingfornowallowyouto:i)testconditionsa ndii)p (schemat-ically)if(condition)statement.

6 Detob eexecutedhasseveralstatementsthenwemustu seablo ckinbraces:if(condition){statement1;stat ement2;}Thereisalsoamoregeneralformwhere wecanincludeanarbitrarynumb erofelseifconditionstob (schematically)if(condition1){statement1 ;statement2;}else if(condition2){statement3;..}else if(condition3){statement5;statement6;}el se{statement7;statement8;} (condition){statements}Theforstatementis similarexceptthatthereisanintegeriterati onvariableoftyp eintwhichkeepsb (int i=0; condition;i++){statements}The rststatementintheargumentinitializesthei terator,thesecondisaconditionthatisteste deachtimetheblo ckstatementsarerep ++op erator, esInthenextchapterwewillgothroughthebuil tindatatyp ++providesanextrafeaturewhichallowstode ethatcandede ,theop erationsonthedataandhowtheclasstyp einteractswithotherclassob jectsisde ewithstd.

7 Cin, ducingclassesatthisstagecanb esInthischapterthebasicdatatyp esofthelanguageandtheop eratorstheysupp esInaddititontothesetyp esthereisthevoidtyp ewhichisusedforexampleasthetyp ereturnedbyafunctionwhichactsonsomevaria blesbutdo (inbits)maydep , esint, bool, char(andthecorresp ondinglongorshortversions)areknownasinte graltyp esandtheyholdintegers,b o olean(true or false)andcharacters(eachcharactervariabl eholdsanumb ercorresp ondingtoacharacter).Typ escanb eforethecorresp ondingtyp :Youshouldb eawareofthelimitsoftherepresentationofth etyp esab (forexampleanintegerthathasto omanydigits),youwillgetavaluethatiscompl etelydi dingyoushouldb ecarefultomakesurethisdo esnothapp enotherwiseyouwillmostde nitelygetwrongresultsandtheco demaystillcompileandrun!

8 Regarding oatingp ointnumb er,thetyp efloatisusuallynotpreciseenoughsoitissta ndardtousedoubleformostnumericalapplicat ions(thoughthelongerversionmayb enecessaryinsomesituations). eratorsThoughintheb o okthisisonlyintro eratorsdep endsonthetyp oatingp ointnumb ersareenteredintheusualwaywithoutorwitha dot ..Inadditiontherearewaysofsp ecifyingifintegersaresigned,unsigned, oatorlong:Otherexamplesincludingscienti esequencewhichstartswithaslash\.Onecanha vesp ecialescap esequencesforsp ecialcharacterssuchas:8 Orageneralisedescap esequenceforanycharacterinthecharacterse t,whichconsistesofaslashwiththenumb erofthecorresp ondingcharacterForexampleforoutput(orlat eronwhenweintro ducestrings),itisusefultonotehowtowritea literalexpressionforanarrayofcharacters.

9 ,b othforcharactersandstrings,aresp eci edbyaddingLb eforethecorresp ecifyingthedatatyp e(whichdeterminestheamountofstorageneede d) , eusedasvariablenames:9 Anotherruleisthatanidenti ers, :whereseveralvariablesofthesametyp earedeclaredonthesameline, jectscanb einitialisedinthefollowingways:Formoreco mplicatedclasstyp es,wewillseelaterthattheremayb emoreformsofinitialisingthecorresp ondingclassob edoneforseveralob jectsinoneline,orwithanarbitrarilycompli catedexpres-sion, , ningit( ).Thisjustdeclaresthepresenceofthevariab lesomewhereintheprogramwhichwillb ede ecomesade erent eofanameAnameofavariable,functionorevend atatyp emayb erestrictedtocertain les,orcertainblo cksofco deandmaynotb eknowntootherblo cksofco esinC++ , while, nedfromtheirp ointofdeclarationandarenotknownoutsideth escop ede ++itisusuallygo o dpracticetode es,whichmayb out:theauthoroftheprogram,theyearandvers ionoftheprogram,Ashortabstractoftheprogr amdescribingwhatitdo es(lo okatthemostsuitablecharactersfromthetabl eintheprevioussections,toformatthetext).

10 Er,usingaforlo ortanerroriftheinputnumb erisnegativeandprintanerrormessage(tryto usetheb ellcharactertoseewhathapp ens). 'shapp erInmanysituationsitisconvenienttode neconstants,forexampleifthereisa xeddimension(whichyoumaywanttochangelate randwouldb eapaintochangeallo ccurencesintheprogram),orafundamentalcon stantinyourproblemanyouwantanerrortoo eandinitialisingtheob :Aconstantislo caltothescop ewhereitisde les,itshouldb edeclaredasexternalinallthe leswhereitisusedandde :ExerciseWriteaprogramwhichcomputesthear eaunderaparab olainaintervalusingatrap rstestimate,andthenrep eatwithawhilelo opwithasmallerstepwhiletheerrorestimate( obtainedbycomparingtothepreviousvalue)is b neconstantsinyourco dewhichhold.


Related search queries