Example: barber

Tutorial on C Language Programming - University …

TutorialonC Iowa, Departmentof ComputerScienceIntroductionto SystemSoftware programmingC programstructure:DatastructureControlstr uctureProgramstructureIntroductionto SystemSoftware :integer(int),smallintegers(short),large integers(long)realnumbers(float),largere alnumbers(double)characterdata(char)User defineddatatypesusingtypeconstructorsarr ay,record,pointer, fileIntroductionto SystemSoftware dataobjectofa definedtypeT is declaredusingtheconstructoftheformT datawhereT is a typeexpressionanddatais thedataobjectnameExample:intx declaresx anobjectoftypeintegershort x declaresx anobjectoftypesmallintegerlongx declaresx anobjectof typelargeintegerfloatx declaresx anobjectof typerealdouble x declaresx anobjectof typelargerealcharx declaresx anobjectoftypecharacterIntroductionto SystemSoftware a userdefinedtypeT is constructedusingoneof thetypeconstructorsstruct,[], *, new userdefinedtypeT is constructedusingthemeta-constructortyped efanda typeora typeconstructorIntroductionto SystemSoftware recordtypeis definedusingthestructconstructorfollowin gthetemplate:structTypeName{component1;c omponent2;component3;}Componentsareobjec tdeclarationsoftheformTObjName;Note:Type Nameis anabstractionIntroductionto SystemSoftware typeTypeNameis obtainedby thedeclarationTypeNameMyRecordOnecanputt ogetherthedefinitionandthedeclarationget ting:structTypeName{com}

Tutorial on C Language Programming Teodor Rus rus@cs.uiowa.edu The University of Iowa, Department of Computer Science Introduction to System Software – p.1/64

Tags:

  Programming, Language, Tutorials, Tutorial on c language programming

Information

Domain:

Source:

Link to this page:

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

Other abuse

Advertisement

Transcription of Tutorial on C Language Programming - University …

1 TutorialonC Iowa, Departmentof ComputerScienceIntroductionto SystemSoftware programmingC programstructure:DatastructureControlstr uctureProgramstructureIntroductionto SystemSoftware :integer(int),smallintegers(short),large integers(long)realnumbers(float),largere alnumbers(double)characterdata(char)User defineddatatypesusingtypeconstructorsarr ay,record,pointer, fileIntroductionto SystemSoftware dataobjectofa definedtypeT is declaredusingtheconstructoftheformT datawhereT is a typeexpressionanddatais thedataobjectnameExample:intx declaresx anobjectoftypeintegershort x declaresx anobjectoftypesmallintegerlongx declaresx anobjectof typelargeintegerfloatx declaresx anobjectof typerealdouble x declaresx anobjectof typelargerealcharx declaresx anobjectoftypecharacterIntroductionto SystemSoftware a userdefinedtypeT is constructedusingoneof thetypeconstructorsstruct,[], *, new userdefinedtypeT is constructedusingthemeta-constructortyped efanda typeora typeconstructorIntroductionto SystemSoftware recordtypeis definedusingthestructconstructorfollowin gthetemplate:structTypeName{component1;c omponent2;component3;}Componentsareobjec tdeclarationsoftheformTObjName;Note:Type Nameis anabstractionIntroductionto SystemSoftware typeTypeNameis obtainedby thedeclarationTypeNameMyRecordOnecanputt ogetherthedefinitionandthedeclarationget ting:structTypeName{component1;component 2;component3;} MyRecord.

2 Introductionto SystemSoftware a recordtypedefinitionanddeclarationis:str uctData{intDay;intMonth;intYear;} MyData,*MyPT,MyArray[Max];Note:typeexpre ssionsareobtainedby combiningthetypeconstructorsstruct,*, [], in a welldefinedmannerIntroductionto SystemSoftware , , arereferencesatthecomponentsof thedataobjectMyDataM yP T > Y ear,M yP T > M onth,M yP T > , we needtouseMyPT= &MyDatabeforethisreferencemake sense; ,M yP T > Y ear ( M yP T):Y SystemSoftware :structexample{int x;int *y;} Obj,*PtObj;Introductionto SystemSoftware representationofObjis in Figure1integeraddressintegerFigure1:Reco rdmemory representationIntroductionto SystemSoftware shownin Figure2integeraddressinteger?integerFigu re2:Pointerto recordmemory representationIntroductionto SystemSoftware give few importantfactsaboutrecords, assumethatPtObj= & theintegerx;P tObj > xis the(integer)addressy;Obj > yis theaddressy;+ +P tObj > xincrementsx notPtObj;(++P t) > xincrementsPtObjbeforeaccessingx;(P tObj+ +) > xincrementsPtObjafteraccessingx P tObj > yfetcheswhatevery pointsto(aninteger); P tObj > y+ +incrementsy afteraccessingwhateverit pointsto(thisis anaddressoperation);( P tObj > y) + +incrementswhatevery pointsto (thisis anintegeroperation);Introductionto SystemSoftware unidimensionalarray of n objectsof typeT is definedbyT UniName[n]Note, thisis botha definitionanda declarationA bidimensionalarray ofm nobjectsof typeT isdefinedbyT BidimName[m][n]Theelementiof thearray UniNameis referencedbyArrayName[i].

3 Note,0<=i < nExamples:intx[20],structexampleMyArray[ 100][100]Introductionto SystemSoftware theelementsof anunidimensionalarrayof size n are0, 1,: : :, n-1 Theelementsofa bidimensionalarrayBidimName[m][n]arestor edin memory ona row-major, , they are:BidimName[0][0],BidimName[0][1],.. BidimName[0][n-1]BidimName[1][0],BidimNa me[1][1],.. BidimName[1][n-1]BidimName[2][0],BidimNa me[2][1],.. BidimName[2][n-1]..BidimName[m-1][0], BidimName[m-1][1],.. BidimName[m-1][n-1]Introductionto SystemSoftware fieldslike in PascalExample:unionUniName{int ival;floatfval;char*pval;} uval,*p;Thevariable uval may have asvalueaninteger, a real,ora pointerto a thevalueholdby theuvalIntroductionto SystemSoftware unionarereferencedin thesameway aselementsofa record(struct)arereferencedThememory representationof variable uval willbelargeenoughtoaccommodateany ofthevaluesthatareusedin itsdefinitionIt is theprogrammer s taskto providea discriminantthatwillshow whatcomponentof a unionis in thevariableuval ata SystemSoftware unionusageThesymboltable entry of a symboltable usedby acompiler:structSymTabEntry{char*name;in tflags;intstype;union{intival;floatfval; char*pval;}sval;} SymTab[MaxSymb],*PtSymTab[MaxSymb];Intro ductionto SystemSoftware [i].

4 ObjectandP tSymTab[i] > Object, whereObject2f name;f lags; stype;svalgarereferencesto symboltable SystemSoftware objecthasanaddress(name)anda valueAnobjectof typepointerhasasitsvaluetheaddressofanob jectofa giventypeAnobjectof typepointeris definedby theconstructT *PtName;where* show thatPtNamedis a pointerandT showsthetypeof objectaddressit may holdIntroductionto SystemSoftware , z; /* x andz arevariablesof typeinteger*/int*y, *w;/* y andw arevariablesoftypepointertointeger*/char v, *p;/* p is a variable of typepointerto character*/Addressofanobjectxof typeT is obtainedby theoperator&, , is &xy = &xis a validassignmentwhiley = x is notIntroductionto SystemSoftware name, indirectby *nameThenameofa variable oftypepointerreferencestheaddressoftheob jectit holds. Hence, w = y is validbutw = p is invalidDereferencingofa variable oftypepointerleadsustothevalueholdin theobjectwhoseaddressis holdbythepointer.

5 Hence, (*y)is theintegerwhoseaddressisin yOperationona variable of typepointer(suchasy) areaddresstypeoperationsOperationsonthev alueoftheobjectswhoseaddressesareholdby pointers(suchas(*y))aredatatypeoperation sIntroductionto SystemSoftware fileis a potentiallyinfinitestreamof objects(characters, integers, reals, strings, arrays, etc)A fileis describedby descriptorthatshows:typeoftheobjectsit containsorderrelationamongitscomponentsa ccessmethodusedto filecomponentsIn C-languagea fileis specifiedby a nameandafile-descriptorFilenameis userdefinedFiledescriptoris obtainedfromthesystemusingthedeclaration FILE*fp;Introductionto SystemSoftware filearea:open,doio, closeFileopenlinksthefileabstractiondefi nedin C thisis donebyfp = fopen(name,mode),wheremodeis "w","r" or "rw"Filecloseremovesthelinksestablishedb y :printf, fprintfstoreobjectsin thefile, andscanfandfscanfaccessobjectsin a fileprintf, fprintf, scanf, fscanfhave a formatethatcanbelearn by inspectingthemanpageof thesefunctionsIntroductionto SystemSoftware definetheirowntypesusingtypedefconstruct Theusagepattern istypedefTypeDefinitionTypeNamewhereType Definitionis thetypeexpressiondefiningthenew typeandTypeNameis thenameofthenew typeObjectsof typeTypeNamearethendeclaredasusualTypeNa mecanalsobeusedascomponentofvarioustypee xpressionsusingconstructorsstruct,[],*, SystemSoftware ;/* LENGTHis a new type*/LENGTHlen,maxlen,*L[];/* variable oftypeLENGTH*/typedefchar*string;/* stringis synonymoustochar* */ stringp,lineptr[L].

6 /* Thesearevariable of typestring*/typedefstructnode{char*value ;intcount;structnode*Left;structnode*Rig ht;} TreeRoot,*TreePTR;TreeRoota;/* a is a variable of typeTreeRoot*/TreePTRb;/* b is a variable oftypeTreeRoot* */Introductionto SystemSoftware StructuresIntroductionto SystemSoftware languagecomputationunitsAssignmentstatem entsBlock statements:{statement1;..;statement}Cont rolstatements:branchingandloopingstateme ntsFunctioncalls;Introductionto SystemSoftware :identifier= expression;Semantics:evaluateexpressiont o val andthenassignval asthevalueofidentifierNote:Typeof val shouldbethesameasthetypeofidentifierPecu liarities:id++is equivalenttoid = id + 1andid- -is equivalenttoid = id - 1C expressionsarearithmeticorlogic;but SystemSoftware SystemSoftware :if (expr)statement; whereexprisbooleanSemantic:evaluateexpre ssionexprtoval;if val is trueexecutestatement, otherwiseexecutenext statementof theprogramIntroductionto SystemSoftware :if (expr)statement1;elsestatement2;Semantic s:evaluateexpressionexprtoval;if val istrueexecutestatement1otherwiseexecutes tatement2; in any casecontrolflowsto thenextstatementoftheprogramIntroduction to SystemSoftware :switch(expr)/* expris a booleanexpression*/{caseC1:{statement0;b reak}caseC2:{statement1;break}.}

7 Default:{DefaultStatement;break}}Semanti c:evaluateexprto val;if val is equalto oneofthecaseconstantsC1,C2,: : :, theassociatedstatementis executed; , defaultclauseis optional;if notthereandval is notequalwithany caseconstant,noactiontake placeIntroductionto SystemSoftware :break;Semantic:terminatestheexecutionof a loopora switchIntroductionto SystemSoftware :continue;Semantic:terminatesthecurrenti terationofa loopIntroductionto SystemSoftware :gotoLabel;whereLabel:Statement;belongst o theprogramSemantic:forcescontrolto goto theStatement;Introductionto SystemSoftware SystemSoftware :while(expr)Statement;whereexprisboolean Semantic:evaluateexprto val;if val is trueStatementis executeandwhilestatementis repeated;if val is falsecontrolflowsto thenext instructionoftheprogramNote:truebooleanv aluesareany integerdifferentfromzero;falsebooleanval ueis SystemSoftware :do Statement;while(expr);Semantic:equivalen ttoStatement;while(Expr)Statement;Note:w hilestatementexecuteszeroor moreiterationsof theloop; SystemSoftware :for(expr1;expr2;expr3)Statement;Semanti c:equivalenttoexpr1;while(expr2){Stateme nt;expr3;}Note:any of theexpressionsexpr1,expr2,expr3maybeomit ted;if expr3is omittedit is interpretedastrue,hencevarioussorts ofinfiniteloopscanbeperformedIntroductio nto SystemSoftware :{Declarationlist;Statementlist;}Declara tionlist:Declaration;DeclarationlistDecl aration;Statementlist:Statement;Statemen tlistStatement;Semantics:statementsin Statementlistareexecutedinsequencein theenvironmentprovidedby DeclarationlistIntroductionto SystemSoftware :typename(formalparameterlist){Declarati onlist;Statementlist.

8 Returnresult}Semantic:a functiondefinitionspecifiesthecomputatio ndefinedby theStatementlistin theenvironmentdefinedby formalparameterlistandDeclarationlistand return a resultoftypetypeIntroductionto SystemSoftware * power:raisesthe valueof variablebaseto /*/* the powervaluesof variablen, n >= 0 */int power(intbase,int n){int i, p;p = 1;for (i = 1; i <= n; i++)p = p * base;returnp;}Note:commentsin C areenclosedin /* ..*/ Usecommentsoutsideof func-tiondefinition;formatefunctionbodys uchthatthetext SystemSoftware :typename(type1,type2,..)wheretypeis thefunctiontype( , thetypeof resultreturnedby thefunction)andtype1,type2,..arethetypes oftheformalparametersSemantics:declarena measthenameof a functionwhoseargumentsareof typestype1,type2,..andwhoseresultif of typetypeNote:sincea functiondeclarationis a declarationit mustbeprovidedin thedeclarationlistof SystemSoftware :identifier= name(actualparameters);identifiermusthav e thesametypeasthetypespecifiedin thedefinitionandthedeclarationofnameActu alparametersmustexpressionswhosevaluesar eofthetypesthattype1,type2.

9 Specifiedin thedefinitionandthedeclarationofnameSema ntic:executecomputationencapsulatedin thedefinitionoffunctionname()in theenvironmentprovidedby actualparametersandreturn :intx; int power(int,int);..;x =power(2,3);..Introductionto SystemSoftware value, exceptarrays, whicharepassedby SystemSoftware reference, , theaddressofthearray variable is operateonthelocalelementsof a functionusingthemasparameterstoanotherfu nctionpointersneedto betransmittedat functioncallInitializationofthepointersi s ,int*x,char*x,structname* SystemSoftware functionis representedin memory by two components:Executioncode, , memory imageofexecutablestatementsActivationrec ordIntroductionto SystemSoftware a datastructureconstgructedby thecompilerandcontains:Functionreturn value;Staticlink:a pointertotheactivationrecordof thefunctionthatcontainsthedefinitionof C thisis :a pointertotheactivationrecordof thefunctionthatcontainsthecallof thefunctionStack extensionvalueReturn addressListoflocationsforactualparameter sLocalvariablesof thefunctionIntroductionto SystemSoftware ofa functioninmemoryFigure3 showsthestructureof a functionin memory:GlobalvariablesExecutable codeActivationrecordr?

10 R?Figure3:Functionmemory representationIntroductionto SystemSoftware ofa C languageprogramA C programis composedof fourcomponentgs:Macrodefinitions(optiona l)Globaldeclarations(optional)Mainfuncti on(mandatory)Otherfunctionscomponentsof theprogram(optional)Introductionto SystemSoftware C programhasfourcomponents:macrodefinition s,globaldeclarations, main()function,andotherfunctions. Onlymain()functionis C languageprogramis executedby theoperatingsystembycallingitsfunctionsm ain().A C languageprogramis implicitlydeclaredto thesystemby thepresenceoftheuniquenames,main()Introd uctionto SystemSoftware definitioncomponentSyntax:sequenceofmacr o-operationsof theform:#definenamevalue#include"filenam e"#include<filename>Semantics:#definenamevalueallowsprogramm erto usenamein theprogramwhilecompilerreplacesit withvaluewhichcanbeany stringof characters.#include"filename"allowsthepr ogrammertodevelopa programonvariousseparatefiles.


Related search queries