C for Python Programmers - Hacettepe...

72
C for Python Programmers BBM 101 - Introduction to Programming I Hacettepe University Fall 2016 Fuat Akal, Aykut Erdem, Erkut Erdem 1 Slides based on the material prepared by Carl Burch (Hendrix College) with modifications by Elizabeth Patitsas (U Toronto)

Transcript of C for Python Programmers - Hacettepe...

CforPythonProgrammers

BBM101- Introduction toProgramming I

Hacettepe UniversityFall2016

FuatAkal,Aykut Erdem,ErkutErdem

1Slides basedonthematerialpreparedbyCarlBurch(HendrixCollege)withmodifications byElizabethPatitsas (UToronto)

Today

• HowPython&Caresimilar• HowPython&Caredifferent– Cfundamentals– CExamples

2

Creatingcomputerprograms

• Eachprogramminglanguageprovidesasetofprimitiveoperations

• Eachprogramminglanguageprovidesmechanismsforcombiningprimitivestoformmorecomplex,butlegal,expressions

• Eachprogramminglanguageprovidesmechanismsfordeducingmeaningsorvaluesassociatedwithcomputationsorexpressions

Slidecredit:E.Grimson, J.Guttag andC.Terman

Recallourgoal

• Learnthesyntaxandsemanticsofaprogramminglanguage

• Learnhowtousethoseelementstotranslate“recipes”forsolvingaproblemintoaform thatthecomputercanusetodo theworkforus

• Computationalmodesofthoughtenableustouseasuiteofmethodstosolveproblems

Slidecredit:E.Grimson, J.Guttag andC.Terman

Recall:DimensionsofaPL• Low-levelvs.High-level– Distinctionaccordingtothelevelofabstraction– Inlow-levelprogramminglanguages(e.g.Assembly),thesetofinstructionsusedincomputationsareverysimple(nearlyatmachinelevel)

– Ahigh-levelprogramminglanguage(e.g.C,Java)hasamuchricherandmorecomplexsetofprimitives.

Recall:DimensionsofaPL• Generalvs.Targeted– Distinctionaccordingtotherangeofapplications– Inageneralprogramminglanguage,thesetofprimitivessupportabroadrangeofapplications.

– Atargetedprogramminglanguage aimsataveryspecificsetofapplications.• e.g.,MATLAB(matrixlaboratory)isaprogramminglanguagespecificallydesignedfornumericalcomputing(matrixandvectoroperations)

Recall:DimensionsofaPL• Interpretedvs.Compiled– Distinctionaccordingtohowthesourcecodeisexecuted– Ininterpretedlanguages(e.g.Python),thesourcecodeisexecuteddirectlyatruntime(bytheinterpreter).• Interpretercontrolthetheflowoftheprogrambygoingthrougheachoneoftheinstructions.

– Incompiledlanguages(e.g.C),thesourcecodefirstneedstobetranslatedtoanobjectcode(bythecompiler)beforetheexecution.

– Morelatertoday!

Recall:DimensionsofaPL• Functional

• Treatscomputationastheevaluationofmathematicalfunctions(e.g.Lisp,Scheme,Haskell,etc.)

• Imperative• describescomputationintermsofstatementsthatchangeaprogramstate(e.g.FORTRAN,BASIC,Pascal,C,etc.)

• Logical(declarative)• expressesthelogicofacomputationwithoutdescribingitscontrolflow(e.g.Prolog)

• Objectoriented• uses"objects"– datastructuresconsistingofdatafieldsandmethodstogetherwiththeirinteractions– todesignapplicationsandcomputerprograms(e.g.C++,Java,C#,Python,etc.)

C(1973)

• DevelopedbyKenThompsonandDennisRitchieatAT&TBellLabsforuseontheUNIXoperatingsystem.– nowusedonpracticallyeveryoperatingsystem– popularlanguageforwritingsystemsoftware

• Features:– Anextremelysimplecorelanguage,withnon-essential

functionalityprovidedbyastandardizedsetoflibraryroutines.– Low-levelaccesstocomputermemoryviatheuseofpointers.

• Cancestors:C++,C#,Java

9Slidecredit:ThomasJ.Cortina

Python

• CreatedbyGuidovanRossum inthelate1980s• Allowsprogramminginmultipleparadigms:object-oriented,structured,functional

• Usesdynamictypingandgarbagecollection

Slidecredit:ThomasJ.Cortina

BuildingasimpleprograminC(ascomparedtoPython)

• Compilersversusinterpreters• Variabledeclarations• Whitespace• The printf() function• Functions

11

Compilersversusinterpreters

• OnemajordifferencebetweenCandPythonishowtheprogramswritteninthesetwolanguages areexecuted.

• WithCprograms,youusuallyusea compiler whenyouarereadytoseeaCprogramexecute.

• Bycontrast,withPython,youtypicallyusean interpreter.

12

Compilersversusinterpreters

• An interpreter readstheuser-writtenprogramandperformsitdirectly.

• A compiler generatesafilecontainingthetranslationoftheprogramintothemachine'snativecode.– Thecompilerdoesnotactuallyexecutetheprogram!– Instead,youfirstexecutethecompilertocreateanativeexecutable,andthenyouexecutethegeneratedexecutable.

13

TheProgrammingProcessinC

• AftercreatingaCprogram,executingitisatwostepprocess:

me@computer:~$ gcc my_program.cme@computer:~$ ./a.out

14

TheProgrammingProcessinC

me@computer:~$ gcc my_program.cme@computer:~$ ./a.out

• invokesthecompiler,named gcc.• Thecompilerreadsthesourcefile my_program.ccontainingtheCcodes

• Itgeneratesanewfilenamed a.out containingatranslationofthiscodeintothebinarycodeusedbythemachine.

15

Compilersversusinterpreters

me@computer:~$ gcc my_program.cme@computer:~$ ./a.out

• tellsthecomputertoexecutethisbinarycode.• Asitisexecutingtheprogram,thecomputerhasnoideathat a.outwasjustcreatedfromsomeCprogram.

16

TheProgrammingProcessinC

Create/EditProgram Compile Execute

“Thecycleendsoncetheprogrammerissatisfiedwiththeprogram,e.g.,performanceandcorrectness-wise.”

Compilersversusinterpreters

• An interpreter readstheuser-writtenprogramandperformsitdirectly.

• A compiler generatesafilecontainingthetranslationoftheprogramintothemachine'snativecode.

• Beingcompiledhassomeradicalimplicationstolanguagedesign.

• CisdesignedsothecompilercantelleverythingitneedstoknowtotranslatetheCprogramwithoutactuallyexecutingtheprogram.

18

Variabledeclarations

• Crequires variabledeclarations, informingthecompileraboutthevariablebeforethevariableisactuallyused.

• InC,thevariabledeclarationdefinesthevariable's type.• NosuchthinginPython!

19

DeclaringaVariable

• Declaringavariableissimpleenough.• Youenterthevariable'stype,somewhitespace,

thevariable'sname,andasemicolon:

double x;

• ValueassignmentissimilartoPython:

x=3;• x willactuallyholdthefloating-pointvalue3.0ratherthanthe

integer3.• However,onceyoudeclareavariabletobeofaparticular

type,youcannotchangeitstype!

20

DeclaringaVariable

• InC,variabledeclarationsbelongatthetopofthefunctioninwhichtheyareused.

• Ifyouforgettodeclareavariable,thecompilerwillrefusetocompiletheprogram:– A variableisusedbutisnotdeclared.

• ToaPythonprogrammer,itseemsapaintohavetoincludethesevariabledeclarationsinaprogram,thoughthisgetseasierwithmorepractice.

21

Whitespace

• InPython,whitespacecharactersliketabsandnewlinesareimportant:– Youseparateyourstatementsbyplacingthemonseparatelines,andyouindicatetheextentofablockusingindentation.

– likethebodyofa while or ifstatement

• Cdoesnotusewhitespaceexceptforseparatingwords.• Moststatementsareterminatedwithasemicolon';',and

blocksofstatementsareindicatedusingasetofbraces,'{'and'}'.

22

WhitespaceCfragmentdisc = b * b - 4 * a * c;if (disc < 0){

num_sol = 0;}else{

t0 = -b / a;if (disc == 0){

num_sol = 1;sol0 = t0 / 2;

}else{

num_sol = 2;t1 = sqrt(disc) / a;sol0 = (t0 + t1) / 2;sol1 = (t0 - t1) / 2;

}}

Pythonequivalentdisc = b * b - 4 * a * cif disc < 0:

num_sol = 0else:

t0 = -b / aif disc == 0:

num_sol = 1sol0 = t0 / 2

else:num_sol = 2t1 = disc ** 0.5 / asol0 = (t0 + t1) / 2sol1 = (t0 - t1) / 2

23

Whitespace• Assaid,whitespaceisinsignificantinC.• Thecomputerwouldbejustashappyifthepreviouscode

fragmentiswrittenasfollows:

disc=b*b-4*a*c;if(disc<0){num_sol=0;}else{t0=-b/a;if(disc==0){num_sol=1;sol0=t0/2;}else{num_sol=2;t1=sqrt(disc/a;sol0=(t0+t1)/2;sol1=(t0-t1)/2;}}

• However,donotwriteyourprogramslikethis!

24

Theprintf()function

• InPython,displayingresultsfortheuserisaccomplishedbyusing print.

• InC,insteadyouusethe printf()functionwhichisprovidedbytheC'sstandardlibrary.

• Thewaytheparametersto printf()work isabitcomplicatedbutalsoquiteconvenient.

25

Theprintf()function

• Thefirstparameterisastringspecifyingtheformatofwhattoprint,andthefollowingparametersindicatethevaluestoprint.

• Considerthefollowingexample:printf("# solns: %d\n", num_sol);

• “# solns: %d\n” istheformatstring,num_sol isthevaluetobeprinted.

• Thepercentcharacterisspecialto printf().– Itsaystoprintavaluespecifiedinasubsequentparameter.– %d forintegers/decimals

• Ifthevaluestoredinnum_sol is2,theoutputis:# solns: 2

26

Theprintf()function

• LikePython,Callowsyoutoincludeescapecharactersinastringusingabackslash:– The“\n”sequencerepresentsthenewlinecharacter,– The“\t”sequencerepresentsthetabcharacter,– “\"”sequence representsthedouble-quotecharacter,– “\\”sequencerepresentsthebackslashcharacter.

• TheseescapecharactersarepartofCsyntax,notpartoftheprintf() function.

27

Theprintf()function

• Let'slookatanotherexample.printf("# of solns: %d\n", num_sol);printf("solns: %f, %f", sol0, sol1);

• Let'sassumenum_sol holds2, sol0 holds4,andsol1 holds1.

• Whenthecomputerreachesthesetwoprintf() functioncalls,itexecutesthemsequentially.

• Theoutputis:# of solns: 2

solns: 4.0, 1.0

28

Theprintf()function

• There'savarietyofcharactersthatcanfollowthepercentcharacterintheformattingstring.– %d,aswe'vealreadyseen,saystoprintan int valueindecimal

form.– %f saystoprinta double valueindecimal-pointform.– %e saystoprinta double valueinscientificnotation(for

example,3.000000e8).– %c saystoprinta char value.– %s saystoprintastring.

• There'snovariabletypeforrepresentingastring,butCdoessupportsomestringfacilitiesusingarraysofcharacters.

29

Functions• UnlikePython,allCcodemustbenestedwithinfunctions,

andfunctionscannotbenestedwithineachother.• ACprogram'soverallstructureistypicallyvery

straightforward.• Itisalistoffunctiondefinitions,oneafteranother,each

containingalistofstatementstobeexecutedwhenthefunctioniscalled.

30

Functions• ACfunctionisdefinedbynamingthereturntype,followedbythefunction

name,followedbyasetofparentheseslistingtheparameters.• Eachparameterisdescribedbyincludingthetypeoftheparameterandthe

parametername.• Here's asimpleexample of afunction definition:

float expon(float b, int e){

if (e == 0){

return 1.0;}else{

return b * expon(b, e - 1);}

}

31

Thisis afunction namedexpon,which takes twoarguments, first afloating pointnumber and next aninteger,and returns afloating pointnumber.

Functions

• Ifyouhaveafunctionthatdoesnothaveanyusefulreturnvalue,thenyou'duse void asthereturntype.

• Programshaveonespecialfunctionnamed main,whosereturntypeisaninteger.

• Thisfunctionisthe“startingpoint”fortheprogram:– Thecomputeressentiallycallstheprogram's main functionwhenitwantstoexecutetheprogram.

– Theintegerreturnvalueislargelymeaningless;we'llalwaysreturn0ratherthanworryingabouthowthereturnvaluemightbeused.

32

FunctionsCprogramint gcd(int a, int b){if (b == 0){

return a;}else{

return gcd(b, a % b);}

}

int main(){printf("GCD: %d\n“, gcd(24,40));return 0;

}

Pythonprogramdef gcd(a, b):if b == 0:

return aelse:

return gcd(b, a % b)

print("GCD: " + str(gcd(24, 40)))

33

Statement-levelconstructs

• Operators• Basictypes• Braces• Statements• Arrays• Comments

34

OperatorsinCMajoroperatorsinCandPython

• Theylooksimilarbuttherearesomesignificantdifferences 35

Coperatorprecedence Pythonoperatorprecedence++ -- (postfix) **+ - ! (unary) + - (unary)* / % * / % //+ - (binary) + - (binary)< > <= >= < > <= >= == !=== != not&& and|| or= += -= *= /= %=

OperatorsinC–ImportantDistinctions

36

• CdoesnothaveanexponentiationoperatorlikePython's**operator.ForexponentiationinC,you'dwanttousethelibraryfunctionpow().Forexample,pow(1.1, 2.0) computes1.1².

• CusessymbolsratherthanwordsfortheBooleanoperationsAND(&&),OR(||),andNOT(!).

• TheprecedencelevelofNOT(the! operator)isveryhighinC.Thisisalmostneverdesired,soyouendupneedingparenthesesmosttimesyouwanttousethe! operator.

OperatorsinC–ImportantDistinctions

• Cdefinesassignmentasanoperator,whereasPythondefinesassignmentasastatement.

• Thevalueoftheassignmentoperatoristhevalueassigned.• AconsequenceofC'sdesignisthatanassignmentcan

legallybepartofanotherstatement.• Example:

– Thevaluereturnedbygetchar() isassignedtothevariablea,– Thevalueassignedtoa istestedwhetheritmatchestheEOF

constant– Itisusedtodecidewhethertorepeattheloopagain.

37

while ((a = getchar()) != EOF)

OperatorsinC–ImportantDistinctions

• Cdefinesassignmentasanoperator,whereasPythondefinesassignmentasastatement.

• Thevalueoftheassignmentoperatoristhevalueassigned.• AconsequenceofC'sdesignisthatanassignmentcan

legallybepartofanotherstatement.• Example:

– Thevaluereturnedbygetchar() isassignedtothevariablea,– Thevalueassignedtoa istestedwhetheritmatchestheEOF

constant– Itisusedtodecidewhethertorepeattheloopagain.

38

while ((a = getchar()) != EOF)

OperatorsinC–ImportantDistinctions

• C'soperators++ and-- areforincrementinganddecrementingavariable.Thus,thestatement“i++”isashorterformofthestatement“i = i + 1”(or“i += 1”).”

• C'sdivisionoperator/ doesintegerdivisionifbothsidesoftheoperatorhaveanint type;thatis,anyremainderisignoredwithsuchadivision.– Thus,inCtheexpression“13/5”evaluatesto2,while“13/5.0” is2.6:Thefirsthasintegervaluesoneachside,whilethesecondhasafloating-pointnumberontheright.

39

BasictypesinC

• C'slistofbasictypesisquiteconstrained.int foranintegerchar forasinglecharacterfloat forasingle-precisionfloating-pointnumberdouble foradouble-precisionfloating-pointnumber

• DataTypeModifiers– signed /unsigned– short /long

40

int

• 4bytes(onUnix)• Base-2representation.• needonebitfor+or-• Range:-231 to231

• Variants:short (2bytes),long (8bytes),unsigned(onlynon-negative)

Slidecredit:BertHuang

char

• 1byte• ASCIIrepresentationinbase-2• Range:0-255(lotsofunused)

Slidecredit:BertHuang

float

• Standsfor“floatingdecimalpoint”• 4bytes• Similartoscientificnotation:4.288*103

• Verydifferentinterpretationofbitsthanint andchar.• Range:-1038 to1038

Slidecredit:BertHuang

NoBooleantypeforrepresentingtrue/false

• Thishasmajorimplicationsforastatementlikeif,whereyouneedatesttodeterminewhethertoexecutethebody.C'sapproachistotreattheinteger0asfalse andallotherintegervaluesastrue.

• Example

44

int main() {int i = 5;if (i) {

printf("in if\n");} else {

printf("in else\n");}return 0;

}

prints“in if”whenexecutedsincethevalueof(i) is5whichisnot0

NoBooleantypeinC!

• C'soperatorsthatlookliketheyshouldcomputeBooleanvalues(like ==,&&,and||)actuallycomputeint valuesinstead.

• Inparticular,theycompute1torepresenttrue and0torepresentfalse.

• Thismeansthatyoucouldlegitimatelytypethefollowingtocounthowmanyofa,b,andcarepositive.

45

pos = (a > 0) + (b > 0) + (c > 0);

NoBooleantypeinC!

• C'soperatorsthatlookliketheyshouldcomputeBooleanvalues(like ==,&&,and||)actuallycomputeint valuesinstead.

• Inparticular,theycompute1torepresenttrue and0torepresentfalse.

• Thismeansthatyoucouldlegitimatelytypethefollowingtocounthowmanyofa,b,andcarepositive.

46

pos = (a > 0) + (b > 0) + (c > 0);

BasicDataTypesType SizeinBytes Rangesigned char 1 -127to+127unsigned char 1 0to255short int 2 -32,767to+32,767unsigned short int 2 0to65535int 4 -32,767to+32,767unsigned int 4 0to65,535long int 8 -2,147,483,647to+2,147,483,647unsigned long int 8 0to4,294,967,295float 4 ~10-37 to~1038

double 8 ~10-307 to~10308

long double 16 ~10-4931 to~104932

Braces

• Severalstatements,liketheif statement,includeabodythatcanholdmultiplestatements.

• Typicallythebodyissurroundedbybraces('{'and'}')toindicateitsextent.Butwhenthebodyholdsonlyasinglestatement,thebracesareoptional.

• Example:

48

if (first > second)max = first;

elsemax = second;

Braces

• Cprogrammersusethisquiteoftenwhentheywantoneofseveralif teststobeexecuted.

• Example:

49

disc = b * b - 4 * a * c;if (disc < 0) {

num_sol = 0;}else {

if (disc == 0) {num_sol = 1;

} else {

num_sol = 2;}

}

Noticethattheelse clausehereholdsjustonestatement(anif…elsestatement),sowecanomitthebracesaroundit.

Braces

• Cprogrammersusethisquiteoftenwhentheywantoneofseveralif teststobeexecuted.

• Example:

50

disc = b * b - 4 * a * c;if (disc < 0) {

num_sol = 0;}else

if (disc == 0) {num_sol = 1;

} else {

num_sol = 2;}

ButthissituationarisesoftenenoughthatCprogrammersfollowaspecialruleforindentinginthiscase— arulethatallowsallcasestobewrittenatthesamelevelofindentation.

Braces

• Cprogrammersusethisquiteoftenwhentheywantoneofseveralif teststobeexecuted.

• Example:

51

disc = b * b - 4 * a * c;if (disc < 0) {

num_sol = 0;}else if (disc == 0) {

num_sol = 1;} else {

num_sol = 2;}

Braces

• Cprogrammersusethisquiteoftenwhentheywantoneofseveralif teststobeexecuted.

• Example:

52

disc = b * b - 4 * a * c;if (disc < 0) {

num_sol = 0;}else if (disc == 0) {

num_sol = 1;} else {

num_sol = 2;}

Statements

1. Variable declarations– Noparallel inPython!– Example:

53

int x;

Statements

2. AnexpressionasastatementTwoforms:– Anoperatorthatchangesavariable'svalue,liketheassignmentoperator(“x = 3;”),theadditionassignmentoperator+=,orthetheincrementoperator++.• Example:

– Afunctioncall,likeastatementthatsimplycallstheprintf() function.• Example:

54

x = y + z;

printf("%d", x);

Statements3. An if statement–WorksverysimilarlytoPython'sif statement– Theonlymajordifferenceisthesyntax:• InC,anif statement'sconditionmustbeenclosedinparentheses,thereisnocolonfollowingthecondition,andthebodyhasasetofbracesenclosingit.• Aswe'vealreadyseen,Cdoesnothaveanelif clauseasinPython;instead,Cprogrammersusetheoptional-braceruleandwrite“else if”.

– Example:55if (x < 0) { printf("negative"); }

Statements

4. Areturn statement– Youcanhaveareturn statementtoexitafunctionwithagivenreturnvalue.

– Orforafunctionwithnoreturnvalue(andavoidreturntype),youwouldwritesimply“return;”.

– Example:

56

return 0;

Statements

5. Awhile statement– Thewhile statementworksidenticallytoPython's,althoughthesyntaxisdifferentinthesamewaythattheif syntaxisdifferent.

– Example:

57

while (i >= 0) {

printf("%d\n", i);i--;

}

Statements

6. Aforstatement– WhilePythonalsohasafor statement,itspurposeanditssyntaxbearscantsimilaritytoC'sforstatement

– Syntax:for (init; test; update)

body;

• Theprogramwillkeepexecutingthebodyinsidethefor aslongastheconditionistrue(nonzero)

• Theinit istestedbeforeeachiterationoftheloop.Theloopterminateswhentheconditionisfalse.

• Theloopiscontrolledbyavariablewhichisinitializedandmodifiedbytheinit andupdate(e.g.incrementoperation)expressions,respectively. 58

Statements

6. Aforstatement(cont’d.)– Example1:

– Example2:

59

for (p = 1; p <= 512; p *= 2){

printf("%d\n", p);}

for (i = 0; i < n; i++) {body

}

for loopsaremostlyusedforcountingoutniterations

Noticehowtheupdateportionoftheforstatementhaschangedto“p *= 2”.

Arrays

• Pythonsupportsmanytypesthatcombinethebasicatomictypesintoagroup:tuples,lists,strings,dictionaries,sets.

• C'ssupportismuchmorerudimentary:Theonly compositetypeisthearray– SimilartoPython'slistexceptthatanarrayinCcannotgrowor

shrink— itssizeisfixedatthetimeofcreation.• Example:

• Anotherwaytomakeanarray,ifyouknowalltheelementsupfront,is:

60

double pops[50];pops[0] = 897934;pops[1] = pops[0] + 11804445;

char vowels[6]={'a','e','i','o','u','y'};

Arrays• Cdoesnothaveansupportforaccessingthelengthofanarrayonceitiscreated;thatis,thereisnothinganalogoustoPython'slen(pops)

• Whathappensifyouaccessanarrayindexoutsidethearray,likeaccessingpops[50]orpops[-100]?– WithPython,thiswillterminatetheprogramwithafriendlymessagepointingtothelineatfaultandsayingthattheprogramwentbeyondthearraybounds.

– Cisnotnearlysofriendly.Whenyouaccessbeyondanarraybounds,itblindlydoesit.

61

Arrays• Example:

• Somesystems(includingsomeLinuxdistributions)wouldplaceiinmemoryjustafterthevals array.

• Wheni reaches5andthecomputerexecutes“vals[i] = 0”,itinfactresetsthememorycorrespondingtoi to0.– Thefor loophasreset,andtheprogramgoesthroughtheloopagain,and

again,repeatedly.– Theprogramneverreachestheprintf functioncall,andtheprogramnever

terminates.62

int main() {int i;int vals[5];

for (i = 0; i <= 5; i++) {vals[i] = 0;

}printf("%d\n", i);return 0;

}

Arrays• Example:

• Somesystems(includingsomeLinuxdistributions)wouldplaceiinmemoryjustafterthevals array.

• Wheni reaches5andthecomputerexecutes“vals[i] = 0”,itinfactresetsthememorycorrespondingtoi to0.– Thefor loophasreset,andtheprogramgoesthroughtheloopagain,and

again,repeatedly.– Theprogramneverreachestheprintf functioncall,andtheprogramnever

terminates.63

int main() {int i;int vals[5];

for (i = 0; i <= 5; i++) {vals[i] = 0;

}printf("%d\n", i);return 0;

}

Comments

• InC'soriginaldesign,allcommentsbeginwithaslashfollowedbyanasterisk(“/*”)andendwithanasteriskfollowedbyaslash(“*/”).

• Thecommentcanspanmultiplelines.• Example:

64

/* gcd - returns the greatest common* divisor of its two parameters */int gcd(int a, int b) {

...

Comments

• C++introducedasingle-linecommentthathasprovensohandythatmostoftoday'sCcompilersalsosupportit.

• Itstartswithtwoslashcharacters(“//”)andgoestotheendoftheline.

• Example:

65

int gcd(int a, int b) {if (b == 0) {return a;

}else {// recurse if b != 0return gcd(b, a % b);

}}

Libraries

• Separatingaprogramintovariousfiles– Functionprototypes– Headerfiles– Constants

66

Functionprototypes

• InC,afunctionmustbedeclaredabovethelocationwhereyouuseit.

• Thecompilerwouldcomplainifafunctioniscalledbeforedefiningit.

• ThereasonisCassumesthatacompilerreadsaprogramfromthetoptobottom.

• Onewaytogetaroundthis,istousefunctionprototyping,writingthefunctionheaderbutomittingthebodydefinition.

67

Functionprototypes• Considerthefollowingexample:

int gcd(int a, int b);

int main(){

printf("GCD: %d\n", gcd(24, 40));return 0;

}

• Byusing function prototypes,we aredeclaring that the function willeventually be defined,butwe arenotdefining it yet.

• The compiler accepts this andobediently compiles the programwith nocomplaints.

68

Linefor the function prototype

Headerfiles

• Largerprogramsspanningseveralfilesfrequentlycontainmanyfunctionsthatareusedmanytimesinmanydifferentfiles.

• Itwouldbepainfultorepeateveryfunctionprototypeineveryfilethathappenstousethefunction.

• Soweinsteadcreateafilecalleda headerfile.

69

Headerfiles

• Aheaderfilecontainseachprototypewrittenjustonce(andpossiblysomeadditionalsharedinformation).

• Theheaderfilescanthenbereferredtoineachsourcefilethatwantstheprototypes.

• Thefileofprototypesiscalledaheaderfile,sinceitcontainsthe“heads”ofseveralfunctions.

• Conventionally,headerfilesusethe .h prefix,ratherthanthe .c prefixusedforCsourcefiles.

70

Headerfiles• Considerthattheprototypeint gcd(int a,int b) isput

intoaheaderfilecalled mathfun.h.• Wecanincorporatethisheaderfileatthetopofmain.c.

#include <stdio.h>#include "mathfun.h"

int main() {printf("GCD: %d\n", gcd(24, 40));return 0;

}

• The#include directivetellsthepreprocessortoreplacethis linewiththecontentsofthefilespecified.– Theanglebracketsareforstandardheaderfilessuchasstdio.h.– Thequotationmarksareforcustom-writtenheaderfilesthatcanbe

foundinthesamedirectoryasthesourcefiles. 71

Constants

• #define directivetellsthepreprocessortosubstituteallfutureoccurrencesofsomewordwithsomethingelse.

• Example:

– Thepreprocessorsautomaticallytranslatetheaboveexpressioninto:

72

#define PI 3.14159printf("area: %f\n", PI * r * r);

printf("area: %f\n", 3.14159 * r * r);