lec10 c for python programmers - Hacettepebbm101/lectures/lec10_c_part1.pdf · Lecture #10–C for...

75
Lecture #10 – C for Python Programmers Erkut Erdem, Aykut Erdem & Aydın Kaya // Fall 2017 BBM 101 Introduction to Programming I

Transcript of lec10 c for python programmers - Hacettepebbm101/lectures/lec10_c_part1.pdf · Lecture #10–C for...

Lecture#10 – CforPythonProgrammers

Erkut Erdem,AykutErdem&AydınKaya//Fall2017

BBM101IntroductiontoProgrammingI

Lasttime… HowtoDevelopaProgram,AlgorithmicComplexity

2

Today

• HowPython&Caresimilar• HowPython&Caredifferent• Variables,Operators,If-ElseStatements,ArraysinC

3

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.

– Atargetedprogramminglanguageaimsataveryspecificsetofapplications.• 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

10Slidecredit:ThomasJ.Cortina

Python

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

• Usesdynamictypingandgarbagecollection

Slidecredit:ThomasJ.Cortina

BuildingasimpleprograminC(ascomparedtoPython)

• Compilersversusinterpreters• Keywords• Variabledeclarations• Arrays• Whitespace andBraces• The printf() function• The scanf() function• If-ElseStatements

12

Compilersversusinterpreters

• OnemajordifferencebetweenCandPythonishowtheprogramswritteninthesetwolanguages areexecuted.

• WithCprograms,youusuallyusea compiler whenyouarereadytoseeaCprogramexecute.

• Bycontrast,withPython,youtypicallyusean interpreter.

13

Compilersversusinterpreters

• An interpreter readstheuser-writtenprogramandperformsitdirectly.

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

14

TheProgrammingProcessinC

• AftercreatingaCprogram,executingitisatwostepprocess:

me@computer:~$ gcc my_program.c –o my_program

me@computer:~$ ./my_program

15

TheProgrammingProcessinC

me@computer:~$ gcc my_program.c –o my_programme@computer:~$ ./my_program

• invokesthecompiler,named gcc.• Thecompilerreadsthesourcefile my_program.ccontainingtheCcodes

• Itgeneratesanewfilenamed my_program containingatranslationofthiscodeintothebinarycodeusedbythemachine.

16

TheProgrammingProcessinC

me@computer:~$ gcc my_program.c –o my_programme@computer:~$ ./my_program

• tellsthecomputertoexecutethisbinarycode.• Asitisexecutingtheprogram,thecomputerhasnoideathat my_program wasjustcreatedfromsomeCprogram.

17

TheProgrammingProcessinC

Create/EditProgram Compile Execute

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

Compilersversusinterpreters

• An interpreter readstheuser-writtenprogramandperformsitdirectly.

• A compiler generatesafilecontainingthetranslationoftheprogramintothemachine'snativecode.

• Beingcompiledhassomeradicalimplicationstolanguagedesign.

• CisdesignedsothecompilercantelleverythingitneedstoknowtotranslatetheCprogramwithoutactuallyexecutingtheprogram.

19

Keywords

• 32wordsdefinedaskeywordsinC• havepredefinedusesandcannotbeusedforanyother

purposeinaCprogram

auto double int structbreak else long switchcase enum register typedefchar extern return unionConst float short unsignedcontinue for signed voiddefault goto sizeof volatiledo if static while

GeneralFormofaCProgram

Preprocessordirectives

Declarations– variablesfunctions

main function{declarations

statements}

ASimpleCProgram

/* Hello world! Example*/

#include <stdio.h>

int main(){

printf(“Hello world!\n”);return 0;

}

Hello world!

Identifiers

• Asequenceofletters,digits,andthespecialcharacter‘_’satisfying:

identifier=α {α +#}*withα={A,…,Z,a,…,z,_},#={0,…,9},and

*means“0ormore”

•Case-sensitive (asinPython)e.g.Ali andali aretwodifferentidentifiers.

• Identifiersareusedfor:– Variablenames– Functionnames

Identifiers(Cont.)• Samplevalididentifiers

x

a1

_xyz_33

integer1

Double

• Sampleinvalididentifiersxyz.1

gx^2

114West

int

pi*r*r

Variabledeclarations

• Crequires variabledeclarations,informingthecompileraboutthevariablebeforethevariableisactuallyused.

• InC,thevariabledeclarationdefinesthevariable's type.

• NosuchthinginPython!

25

DeclaringaVariable

• Declaringavariableissimpleenough.

• Youenterthevariable'stype,somewhitespace,thevariable'sname,andasemicolon:

double x;

• ValueassignmentissimilartoPython:x=3;

• x willactuallyholdthefloating-pointvalue3.0ratherthantheinteger3.

• However,onceyoudeclareavariabletobeofaparticulartype,youcannotchangeitstype!

26

DeclaringaVariable

• InC,variabledeclarationsbelongatthetopofthefunctioninwhichtheyareused.

• Ifyouforgettodeclareavariable,thecompilerwillrefusetocompiletheprogram:

– A variableisusedbutisnotdeclared.

• ToaPythonprogrammer,itseemsapaintohavetoincludethesevariabledeclarationsinaprogram,thoughthisgetseasierwithmorepractice.

27

VariableDeclarations(Cont.)

• Adeclarationconsistsofadatatypenamefollowedbyalistof(oneormore)variablesofthattype:char c;int ali, bora;float rate;double trouble;

• Avariablemaybeinitializedinitsdeclaration.char c = ‘a’;int a = 220, b = 448;float x = 1.23e-6; /*0.00000123*/double y = 27e3; /*27,000*/

VariableDeclarations(Cont.)

#include <stdio.h>

int main(){

int a;double b;char c;float d;

printf("int: %d \n",a);printf("double: %lf \n",b);printf("char: %c \n",c);printf("float: %f \n",a);return 0;

} 29

• Variablesthatarenotinitializedmayhavegarbagevalues.

ForonlineCeditor:Tutorialspoint

BasictypesinC

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

• DataTypeModifiers– signed /unsigned– short /long

30

BasicDataTypes

Type 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

NoBooleantypeforrepresentingtrue/false

• Thishasmajorimplicationsforastatementlikeif,whereyouneedatesttodeterminewhethertoexecutethebody.C'sapproachistotreattheinteger0asfalse andallotherintegervaluesastrue.

• Example

32

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.

33

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

NoBooleantypeinC!

• Thisquirk— thatCregardsallnon-zerointegersastrue— isgenerallyregardedasamistake,anditleadstoconfusingprograms,somostexpertCprogrammersavoidusingtheshortcut,preferringinsteadtoexplicitlycomparetozeroasamatterofgoodprogrammingstyle.

• Youmayuseexternallibrary«stdbool.h»ordefineyourownconstant(we’llseelater)astrueandfalse.

34

ArithmeticOperators

MajoroperatorsinCandPython

• Theylooksimilarbuttherearesomesignificantdifferences 35

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

ArithmeticOperators

• Forarithmeticcalculations– Use+ foraddition,- forsubstraction,* formultiplicationand/ fordivision

– Integerdivisiontruncatesremainder• 7 / 5 evaluatesto1

– Modulusoperator(%)returnstheremainder• 7 % 5 evaluatesto2

• Arithmeticoperatorsassociatelefttoright.• Operatorprecedence– Example:Findtheaverageofthreevariablesa,b andc

• Donotuse:a + b + c / 3

• Use:(a + b + c ) / 3

ArithmeticOperators(Cont.)Operator(s) Operation(s) Orderofevaluation(precedence)

() Parentheses Evaluatedfirst.Iftheparenthesesarenested,theexpressionintheinnermostpairisevaluatedfirst.Ifthereareseveralpairsofparentheses“onthesamelevel”(i.e.,notnested),theyareevaluatedlefttoright.

*,/,or% Multiplication,Division,Modulus

Evaluatedsecond.Ifthereareseveral,theyareevaluatedlefttoright.

+ or- AdditionSubtraction

Evaluatedlast.Ifthereareseveral,theyareevaluatedlefttoright.

38

LogicalOperators• && (logicalAND)

– Returnstrue ifbothconditionsaretrue

• || (logicalOR)– Returnstrue ifeitherofitsconditionsaretrue

• ! (logicalNOT,logicalnegation)– Reversesthetruth/falsityofitscondition– Unaryoperator,hasoneoperand

• UsefulasconditionsinloopsExpression Result

true && false falsetrue || false true

!false true

39

AllOperatorsOperators Associativity Type ++ -- + - ! (type) right to left unary * / % left to right multiplicative + - left to right additive < <= > >= left to right relational == != left to right equality && left to right logical AND || left to right logical OR ?: right to left conditional = += -= *= /= %= right to left assignment , left to right comma Operator precedence and associativity.

OperatorsinC– ImportantDistinctions

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

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

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

40

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.

41

OperatorsinC- Example

42

#include <stdio.h>#include <math.h>

int main(){

int a = 5, b = 6, c = 10;float p;

p = ((a == 5) + (b < 10) + (c > 15) ) * (c++) / (++b);

printf("p = %f\n", p);

a = 5, b = 6, c = 10;

p = ((a == 5) + (b < 10) + (c > 15) ) * (c++) / (float)(++b);

printf("p = %f\n", p);

// you have to include math.h for pow functionprintf("Value 4.2 ^ 2 = %lf\n", pow(4.2, 2));

}

ForonlineCeditor:Tutorialspoint

OperatorsinC– ImportantDistinctions

• Cdefinesassignmentasanoperator,whereasPythondefinesassignmentasastatement.

• Thevalueoftheassignmentoperatoristhevalueassigned.

• AconsequenceofC'sdesignisthatanassignmentcanlegallybepartofanotherstatement.

• Example:

43

#include <stdio.h>

int main(){

char a;while((a=getchar()) != 'e'){

printf("char: %c\n", a);}return 0;

}

TypeConversionandCasting

• Inanoperation,ifoperandsareofmixeddatatypes,thecompilerwillconvertoneoperandtoagreewiththeotherusingthefollowinghierarchystructure:long double (highest)double

float

long

intchar/short (lowest)

charshort

int long float doublelong double

TypeConversionandCasting(Cont.)

• implicit(automatic)typeconversion– doneautomaticallybythecompilerwheneverdatafromdifferenttypesisintermixed.

– int i;double x = 17.7;i = x;

– float x;int i = 17;x = i;

i=17

x=17.0

TypeCastingExample

46

#include <stdio.h>

int main(){

int a = 17;float b = 2.275;char c = 'B', d = 'e';

printf("Integer value of b is %d\n" , (int)b);printf("Float value of a is %f\n", (float)a);printf("Int value(ASCII code) of c variable is %d\n", (int)c);printf("Double value(ASCII code) of d variable is %lf\n", (double)d);

printf("\n\n");

return 0;

}

ForonlineCeditor:Tutorialspoint

Whitespace

• InPython,whitespacecharactersliketabsandnewlinesareimportant:– Youseparateyourstatementsbyplacingthemonseparatelines,andyouindicatetheextentofablockusingindentation.

– likethebodyofawhile or ifstatement

• Cdoesnotusewhitespaceexceptforseparatingwords.• Moststatementsareterminatedwithasemicolon';',and

blocksofstatementsareindicatedusingasetofbraces,'{'and'}'.

47

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

48

Whitespace

• Assaid,whitespaceisinsignificantinC.• Thecomputerwouldbejustashappyifthepreviouscodefragmentiswrittenasfollows:

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!

49

Theprintf()function

• InPython,displayingresultsfortheuserisaccomplishedbyusing print.

• InC,insteadyouusethe printf()functionwhichisprovidedbytheC'sstandardlibrary.

• Thewaytheparametersto printf()workisabitcomplicatedbutalsoquiteconvenient.

50

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

51

Theprintf()function

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

• TheseescapecharactersarepartofCsyntax,notpartoftheprintf() function.

52

Theprintf()function

• Let'slookatanotherexample.

printf("N. of solns: %d\n", num_sol);printf("solns: %f, %f", sol0, sol1);

• Let'sassume num_sol holds2, sol0 holds4,and sol1 holds1.

• Whenthecomputerreachesthesetwoprintf() functioncalls,itexecutesthemsequentially.

• Theoutputis:N. of solns: 2

solns: 4.0, 1.0

53

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.

54

Theprintf()example

55

#include <stdio.h>

int main(){

char ch = 'A';char str[15] = "sample str";float flt = 10.234;int no = 150;double dbl = 20.123456;

printf("Character is %c \n", ch);printf("String is %s \n" , str);printf("Float value is %f \n", flt);printf("Integer value is %d\n" , no);printf("Double value is %lf \n", dbl);printf("Octal value is %o \n", no);printf("Hexadecimal value is %x \n", no);

return 0;}

ForonlineCeditor:Tutorialspoint

Thescanf()function

• InPython,obtainingvaluefrom theuser (bystandardinput) isaccomplishedbyusing input.

• InC,insteadyouusethe scanf()functionwhichisprovidedbytheC'sstandardlibrary.

• Thewaytheparametersto scanf()workisquitesimilarwithprintf()function.

56

Thescanf()function

• Thefirstparameterisastringspecifyingtheformatofwhattoprint touser.

• Considerthefollowingexample:int age;printf("Enter your age:");scanf("%d", &age);

• Theformatspecifier%d isusedinscanf() statement.Sothat,thevalueenteredisreceivedasanintegerand%s forstring.

• Ampersandisusedbeforevariablename“ch”inscanf() statementas&ch.

57

Thescanf()function

• & charactermeans,storethevalueonthevariablesaddresspositiononmemory.Wewilltalkaboutitlater.

printf("Enter any character \n");scanf("%c", &ch);printf("Entered character is %c \n", ch);printf("Enter any string (upto 100 character )\n");scanf("%s", &str);printf("Entered string is %s \n", str);int anInt; long l;scanf("%d %ld", &anInt, &l);

58

IfElseStatements

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

– Example:

59

if (x < 0) { printf("negative"); }

Braces (exampleonIfElse)

• Severalstatements,liketheif statement,includeabodythatcanholdmultiplestatements.

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

• Example:

60

if (first > second)max = first;

elsemax = second;

Braces (exampleonIfElse)

• Cprogrammersusethisquiteoftenwhentheywantoneofseveralif teststobeexecuted.

• Example:

61

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 (exampleonIfElse)

• Cprogrammersusethisquiteoftenwhentheywantoneofseveralif teststobeexecuted.

• Example:

62

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 (exampleonIfElse)

• Cprogrammersusethisquiteoftenwhentheywantoneofseveralif teststobeexecuted.

• Example:

63

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

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

num_sol = 1;} else {

num_sol = 2;}

Arrays

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

• C'ssupportismuchmorerudimentary:Theonly compositetypeisthearray– SimilartoPython'slistexceptthatanarrayinCcannotgrowor

shrink— itssizeisfixedatthetimeofcreation.• Example:

• Anotherwaytomakeanarray,ifyouknowalltheelementsupfront,is:

64

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

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

DefiningArrays• Whendefiningarrays,specify

• Name• Typeofarray• Numberofelements

arrayType arrayName[numberOfElements];

Examples:int c[10]; float myArray[3284];

• Definingmultiplearraysofsametype• Formatsimilartoregularvariables• Example:

int b[100], x[27];

16.0 12.0 6.0 8.0 2.5 12.0 14.0 -54.5

x[0] x[1] x[2] x[3] x[4] x[5] x[6] x[7]

double x[8];

i=5x[i-1] = x[i]x[i] = x[i+1]x[i]-1 = x[i] Illegalassignmentstatement!

DefiningArrays

ExamplesUsingArrays• Initializers

int n[5] = {1, 2, 3, 4, 5};

− Ifnotenoughinitializers,rightmostelementsbecome0 int n[5] = { 0 }Allelements0

− Carrayshavenoboundschecking

• Ifsizeomitted,initializersdetermineitint n[ ] = { 1, 2, 3, 4, 5 };

− 5initializers,therefore5elementarray

Arrays

• Cdoesnothaveansupportforaccessingthelengthofanarrayonceitiscreated;thatis,thereisnothinganalogoustoPython'slen(pops)– But you may find the length by sizeof function. We’ll discuss it later.

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

– Cisnotnearlysofriendly.Whenyouaccessbeyondanarraybounds,itblindlydoesit.

68

16.0 12.0 6.0 8.0 2.5 12.0 14.0 -54.5

x[0] x[1] x[2] x[3] x[4] x[5] x[6] x[7]

double x[8];

i=5

printf(“%.1f”, x[i]+1);

printf(“%.1f”, x[i]+i);

printf(“%.1f”, x[i+1]);

printf(“%.1f”, x[i+i]);

printf(“%.1f”, x[2*i]);

printf(“%.1f”, x[2*i-3]);

printf(“%.1f”, x[(int)x[4]]);

printf(“%.1f”, x[i++]);

printf(“%.1f”, x[--i]);

13.017.0

14.0

invalid

invalid

-54.5

6.0

12.0

12.0

ExamplesUsingArrays

Arraysexample

70

#include <stdio.h>

int main(){

int a[10];

printf(" Element at index %d : %d \n", 0 , a[0]);printf(" Element at index %d : %d \n", 1 , a[1]);printf(" Element at index %d : %d \n", 55 , a[55]);printf(" Element at index %d : %d \n", -50 , a[-50]);

}

ForonlineCeditor:Tutorialspoint

Arrays– Warning!

• Thelackofarray-boundscheckingcanleadtoverydifficultbugs,whereavariable'svaluechangesmysteriouslysomewherewithinhundredsoffunctions,andyouastheprogrammermustdeterminewhereanarrayindexwasaccessedoutofbounds.Thisisthetypeofbugthattakesalotoftimetouncoverandrepair.

• Everyonceinawhile,you'llseeaCprogramcrash,withamessagelike“segmentationfault”.Itwon'thelpfullyincludeanyindicationofwhatpartoftheprogramisatfault:allyougetisthosethose twowords.Sucherrorsusuallymeanthattheprogramattemptedtoaccessaninvalidmemorylocation.Thismayindicateanattempttoaccessaninvalidarrayindex.

71

Comments

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

• Thecommentcanspanmultiplelines.• Example:

72

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

...

Comments

• C++introducedasingle-linecommentthathasprovensohandythatmostoftoday'sCcompilersalsosupportit.

• Itstartswithtwoslashcharacters(“//”)andgoestotheendoftheline.

• Example:

73

...

// assign sth. to xx= a * r * r;...

Constants

• #define directivetellsthepreprocessortosubstituteallfutureoccurrencesofsomewordwithsomethingelse.

• Youcanuse const prefixtodeclareconstants.• Example:

– Thepreprocessorsautomaticallytranslatetheaboveexpressioninto:

74

#define PI 3.14159

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

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

Constants – True/False

75

#include <stdio.h>

#define TRUE 1#define FALSE 0

int main(){

const int ANOTHER_TRUE = 1;const int ANOTHER_FALSE = 0;

if(ANOTHER_TRUE == TRUE){printf(" It’s True!!! ");

}else{printf(" It’s False :( ");

}return 0;

}

ForonlineCeditor:Tutorialspoint