Example: marketing

Introduction to C++ (and C) Programming

IntroClassesE ciencyOOPI ntroductionto C++(andC)ProgrammingHansPetterLangtangen 1; Informatics, Oslo2 January LangtangenIntroductionto C++(andC)ProgrammingIntroClassesE ciencyOOPO utline1 Introto C++programmingAboutC andC++Introductory C++exampleManipulatedata lesMatrix-vector productTheC preprocessorExercisesAboutclassesin C++A simpleclass2 ClassprogrammingClassComplexA vector classStandard TemplateLibrary3E ciency;C++ :ODEsolversClassesfor LangtangenIntroductionto C++(andC)ProgrammingIntroClassesE ciencyOOPC ontentsGentleintroductionto C++FileI/OArrays andloopsDetailedexplanationof classeswithbuilt-inarithmeticsComputatio nale ciencyaspectsObject-orientedprogramminga ndclasshierarchiesUsingC++objectsin LangtangenIntroductionto C++(andC)ProgrammingIntroClassesE ciencyOOPR equiredbackgroundProgrammingexperiencewi theitherJavaor Fortran/MatlabInterestin numericalcomputingwithC++Interestin low-leveldetailsof thecomputerKnowledgeof someC is advantageous(butnotrequired) LangtangenIntroductionto C++(andC)ProgrammingIntroClassesE ciencyOOPA boutlearningC++C++is a complicatedcomputerlanguageIt takes timeto masterC++{ oneyear is theruleof thumbFou}

Programming experience with either Java or Fortran/Matlab Interest in numerical computing with C++ Interest in low-level details of the computer Knowledge of some C is advantageous (but not required) H. P. Langtangen Introduction to C++ (and C) Programming

Tags:

  Introduction, Programming, Java

Information

Domain:

Source:

Link to this page:

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

Other abuse

Transcription of Introduction to C++ (and C) Programming

1 IntroClassesE ciencyOOPI ntroductionto C++(andC)ProgrammingHansPetterLangtangen 1; Informatics, Oslo2 January LangtangenIntroductionto C++(andC)ProgrammingIntroClassesE ciencyOOPO utline1 Introto C++programmingAboutC andC++Introductory C++exampleManipulatedata lesMatrix-vector productTheC preprocessorExercisesAboutclassesin C++A simpleclass2 ClassprogrammingClassComplexA vector classStandard TemplateLibrary3E ciency;C++ :ODEsolversClassesfor LangtangenIntroductionto C++(andC)ProgrammingIntroClassesE ciencyOOPC ontentsGentleintroductionto C++FileI/OArrays andloopsDetailedexplanationof classeswithbuilt-inarithmeticsComputatio nale ciencyaspectsObject-orientedprogramminga ndclasshierarchiesUsingC++objectsin LangtangenIntroductionto C++(andC)ProgrammingIntroClassesE ciencyOOPR equiredbackgroundProgrammingexperiencewi theitherJavaor Fortran/MatlabInterestin numericalcomputingwithC++Interestin low-leveldetailsof thecomputerKnowledgeof someC is advantageous(butnotrequired) LangtangenIntroductionto C++(andC)

2 ProgrammingIntroClassesE ciencyOOPA boutlearningC++C++is a complicatedcomputerlanguageIt takes timeto masterC++{ oneyear is theruleof thumbFourdays canonlygivea tasteof C++Youneedto work intensivelywithC++in yourownprojectsto masterthelanguageC++exposesyouto lotsof \low-leveldetails"{ thesearehiddenin languageslike java ,MatlabandPythonHopefully, youwillappreciatethespeedand exibility of C++ LangtangenIntroductionto C++(andC)ProgrammingIntroClassesE ciencyOOPT eachingphilosophyIntensivecourse:Lecture s9-12 Hands-ontraining13-16 Learn fromdissectingexamplesGetin touchwiththedirty workGetsomeoverviewof advancedtopicsFocusonprinciplesandgeneri cstrategiesContinuedlearningonindividual basisThiscoursejustgetsyoustarted- usetextbooks,referencemanualsandsoftware examplesfromtheInternetfor LangtangenIntroductionto C++(andC)ProgrammingIntroClassesE ciencyOOPR ecommendedattitudeDiveintoexecutableexam plesDon'ttryto understandeverythingTry to adaptexamplesto newproblemsLook uptechnicaldetailsin manuals/textbooksLearn ondemandStay LangtangenIntroductionto C++(andC)ProgrammingIntroClassesE ciencyOOPC/C++HelloWorldI/OA*xMacrosExer cisesClassesSimpleclassWhydoyouneedto learn \old"compiledlanguages?}}

3 BecauseC, C++,andFortran(77/95)are themoste cientexistingtoolsfor intensivenumericalcomputingBecausetonsof fastandwell-testedcodesare availableinFortran,C/C++Newer languageshaveemphasizedsimplicity andreliability {at thecostof computationale ciencyTo getspeed,youneedto diveintothedetailsof compiledlanguages,andthiscourseis a rst, LangtangenIntroductionto C++(andC)ProgrammingIntroClassesE ciencyOOPC/C++HelloWorldI/OA*xMacrosExer cisesClassesSimpleclassCC is a dominatinglanguagein UnixandWindowsenvironmentsTheC syntaxhasinspiredlotsof popular languages(Awk,C++, java ,Perl,Python,Ruby) Numeroustools(numericallibraries, ,MPI)are writteninC; interfacingthemrequiresC knowledgeC is extremelyportable;\all"machinescancompil eandrunCprogramsC is verylow levelandcloseto themachineUnlimitedpossibilities;onecand oanythingin CProgrammersof high-levellanguagesoftengetconfusedbystr ange/unexpectederrors in LangtangenIntroductionto C++(andC)ProgrammingIntroClassesE ciencyOOPC/C++HelloWorldI/OA*xMacrosExer cisesClassesSimpleclassC++C++extendsC withnicersyntax:-declare variableswhereveryouwant-in/outfunctiona rgumentsusereferences(insteadof pointers)classesfor implementinguser-de neddatatypesa standard library (STL)for frequentlyuseddatatypes (list,stack,queue,vector, hash,string,complex.)}

4 Object-orientedprogramminggenericprogram ming, ,parameterizationof variabletypesviatemplatesexceptionsfor error handlingC is a subsetof C++ LangtangenIntroductionto C++(andC)ProgrammingIntroClassesE ciencyOOPC/C++HelloWorldI/OA*xMacrosExer cisesClassesSimpleclassC versusotherlanguagesFortran77 is more primitivebutmore reliableMatlabis as simple/primitiveas Fortran77,butwithmanymore high-levelcommands(=easyto use)C++is a supersetof C andmuchricher/higher-level/reliableJavai s simplerandmore reliablethanC++Pythonis evenmore high-level,butpotentiallyslowFortran90/9 5is simplerthanJava/C++anda goodalternativeto LangtangenIntroductionto C++(andC)ProgrammingIntroClassesE ciencyOOPC/C++HelloWorldI/OA*xMacrosExer cisesClassesSimpleclassSpeedof C versusspeedof otherlanguagesC is regardedas veryfastFortran77 may yieldslightlyfastercodeC++andFortran90/9 5are in generalslower,butC++isverycloseto C in speedJavais LangtangenIntroductionto C++(andC)ProgrammingIntroClassesE ciencyOOPC/C++HelloWorldI/OA*xMacrosExer cisesClassesSimpleclassSomeguidelinesC programmersneedto be concernedwithlow-leveldetailsthatC++(and Javaor Fortran)programmerscanomitDon'tuseC unlessyouhaveto - useC++insteadThebestsolutionis oftento combinelanguages.

5 Pythontoadministeruserinterfaces,I/Oandc omputations,withintensivenumericsimpleme ntedin C++or LangtangenIntroductionto C++(andC)ProgrammingIntroClassesE ciencyOOPC/C++HelloWorldI/OA*xMacrosExer cisesClassesSimpleclassHighvs low levelprogramsGoal:make a window onthescreenwiththetext\HelloWorld"Implem entationsin1C andtheX11library2C++ LangtangenIntroductionto C++(andC)ProgrammingIntroClassesE ciencyOOPC/C++HelloWorldI/OA*xMacrosExer cisesClassesSimpleclassC/X11implementati on(1)#include< >#include<X11 >#include<X11 >#defineSTRING"Hello,world"#defineBORDER1 #defineFONT"fixed"XWMH intsxwmh= {(InputHint|StateHint),/* flags*/False,/* input*/NormalState,/* initial_state*/0,/* iconpixmap*/0,/* iconwindow*/0, 0,/* iconlocation*/0,/* iconmask*/0,/* Windowgroup*/}; LangtangenIntroductionto C++(andC)ProgrammingIntroClassesE ciencyOOPC/C++HelloWorldI/OA*xMacrosExer cisesClassesSimpleclassC/X11implementati on(2)main(argc,argv)intargc;char**argv;{ Display*dpy;/* X serverconnection*/Windowwin;/* WindowID */GCgc;/* GC to drawwith*/XFontStruct*fontstruct;/* Fontdescriptor*/unsignedlongfth,pad;/* Fontsizeparameters*/unsignedlongfg,bg,bd ;/* Pixelvalues*/unsignedlongbw;/* Borderwidth*/XGCV aluesgcv;/* StructforcreatingGC */XEventevent;/* Eventreceived*/XSizeHintsxsh;/* Sizehintsforwindowmanager*/char*geomSpec ;/* Windowgeometrystring*/XSetWindowAttribut esxswa;/* */if ((dpy= XOpenDisplay(NULL))== NULL){fprintf(stderr,"%s:can'topen%s\en" ,argv[0],XDisplayName(NULL));exit(1).}}

6 } LangtangenIntroductionto C++(andC)ProgrammingIntroClassesE ciencyOOPC/C++HelloWorldI/OA*xMacrosExer cisesClassesSimpleclassC/X11implementati on(3)if ((fontstruct= XLoadQueryFont(dpy,FONT))== NULL){fprintf(stderr,"%s:display%s doesn'tknowfont%s\en",argv[0],DisplayStr ing(dpy),FONT);exit(1);}fth= fontstruct-> +fontstruct-> ;bd = WhitePixel(dpy,DefaultScreen(dpy));bg = BlackPixel(dpy,DefaultScreen(dpy));fg = WhitePixel(dpy,DefaultScreen(dpy));pad= BORDER;bw = 1; (PPosition| PSize); fth+ pad* 2; XTextWidth(fontstruct,STRING,strlen(STRI NG))+ pad* 2; (DisplayWidth(dpy,DefaultScreen(dpy)) )/2; (DisplayHeight(dpy,DefaultScreen(dpy)) )/2;win= XCreateSimpleWindow(dpy,DefaultRootWindo w(dpy), , , , ,bw,bd,bg); LangtangenIntroductionto C++(andC)ProgrammingIntroClassesE ciencyOOPC/C++HelloWorldI/OA*xMacrosExer cisesClassesSimpleclassC/X11implementati on(4)XSetStandardProperties(dpy,win,STRI NG,STRING,None,argv,argc, XSetWMHints(dpy,win, DefaultColormap(dpy,DefaultScreen(dpy)); CenterGravity;XChangeWindowAttributes(dp y,win,(CWColormap| CWBitGravity), fontstruct->fid; fg; bg;gc = XCreateGC(dpy,win,(GCFont| GCForeground| GCBackground), XSelectInput(dpy,win,ExposureMask);XMapW indow(dpy,win); LangtangenIntroductionto C++(andC)ProgrammingIntroClassesE ciencyOOPC/C++HelloWorldI/OA*xMacrosExer cisesClassesSimpleclassC/X11implementati on(5)/** Loopforever,examiningeachevent.))))

7 */while(1){XNextEvent(dpy, if ( Expose&& 0) {XWindowAttributesxwa;intx, y;while(XCheckTypedEvent(dpy,Expose, if (XGetWindowAttributes(dpy,win,&xwa)== 0)break;x = ( XTextWidth(fontstruct,STRING,strlen(STRI NG)))/ 2;y = ( + fontstruct-> fontstruct-> )/ 2;XClearWindow(dpy,win);XDrawString(dpy, win,gc,x, y, STRING,strlen(STRING));}}exit(1);} LangtangenIntroductionto C++(andC)ProgrammingIntroClassesE ciencyOOPC/C++HelloWorldI/OA*xMacrosExer cisesClassesSimpleclassC++/Qtimplementat ion#include< >#include< >intmain(intargc,char*argv[]){QApplicatio na(argc,argv);QLabelhello("Helloworld!", 0); (100,30); ( (); ();}Point:C++o ersabstractions, ,complicatedvariablesthathidelotsof is o eredby LangtangenIntroductionto C++(andC)ProgrammingIntroClassesE ciencyOOPC/C++HelloWorldI/OA*xMacrosExer cisesClassesSimpleclassPythonimplementat ion#!))))

8 /usr/bin/envpythonfromTkinterimport*root = Tk()Label(root,text='Hello,World!',foreg round="white",background="black").pack() ()Similar solutionsare o eredby Perl,Ruby, Scheme, LangtangenIntroductionto C++(andC)ProgrammingIntroClassesE ciencyOOPC/C++HelloWorldI/OA*xMacrosExer cisesClassesSimpleclassTHEtextbook onCKernighanandRitchie:TheC LangtangenIntroductionto C++(andC)ProgrammingIntroClassesE ciencyOOPC/C++HelloWorldI/OA*xMacrosExer cisesClassesSimpleclassRecommendedC++tex tbooksStroustrup,Barton& Nackman,or Yang:More booksreviewed: LangtangenIntroductionto C++(andC)ProgrammingIntroClassesE ciencyOOPC/C++HelloWorldI/OA*xMacrosExer cisesClassesSimpleclassThe rstC++encounterLearningby doing:Scienti cHelloWorld:the rstglimpseof C++Data lter:readingfromandwritingto les,callingfunctionsMatrix-vector product.

9 Arrays,dynamicmemory management,for-loops,subprogramsWe mainlyteachC++{ theC versionspecialitiesare discussedattheendof eachexample(inthisway youlearn quitesomeC withlittleextrae ort) LangtangenIntroductionto C++(andC)ProgrammingIntroClassesE ciencyOOPC/C++HelloWorldI/OA*xMacrosExer cisesClassesSimpleclassScienti cHelloWorldin C++Usage:. :Hello,World!sin( )= learn:1store the rstcommand-lineargumentin a oating-pointvariable2callthesinefunction 3writea combinationof textandnumbersto standard LangtangenIntroductionto C++(andC)ProgrammingIntroClassesE ciencyOOPC/C++HelloWorldI/OA*xMacrosExer cisesClassesSimpleclassThecode#include<iostream>// input/outputfunctionality#include< >// thesinefunction#include< >// theatoffunctionintmain(intargc,char*argv []){// convertthetextargv[1]to doubleusingatof:doubler = atof(argv[1]);// declarevariableswhereverneeded:doubles = sin(r);std::cout<< "Hello,World!}}

10 Sin("<< r << ")="<< s << '\n';return0;/* success*/}File:src/C++/ (C++ ,.C ) LangtangenIntroductionto C++(andC)ProgrammingIntroClassesE ciencyOOPC/C++HelloWorldI/OA*xMacrosExercisesClassesSimpleclassDissection(1)Thecompilermustseea declarationof a functionbefore youcancallit (thecompilercheckstheargumentandreturntypes)Thedeclarationof library functionsappears in \header les"thatmustbe includedin theprogram:#include< >// thesinefunctionWe usethreefunctions(atof,sin, andstd::cout<<; theseare declaredin threedi erentheader lesCommentsappear after//ona lineor between/*and*/(anywhere)Onsomesystems, les(.h)is always a LangtangenIntroductionto C++(andC)ProgrammingIntroClassesE ciencyOOPC/C++HelloWorldI/OA*xMacrosExer cisesClassesSimpleclassDissection(2)Them ainprogramis a functioncalledmainThecommand-lineargumen tsare transferredto themainfunction:intmain(intargc,char*arg v[])argcis thenoof command-linearguments+ 1argvis a vector of stringscontainingthecommand-lineargument sargv[1],argv[2].)


Related search queries