Top Banner

of 36

C Programming 001

Jun 03, 2018

Download

Documents

SidduTadapalli
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 8/12/2019 C Programming 001

    1/36

    Chapter 1: Introduction

    C is (as K&R admit) a relatively small language, but one which (to itsadmirers, anyway) wears well. C's small, unambitious feature set is a real

    advantage: there's less to learn there isn't e!cess baggage in the way when youdon't need it. "t can also be a disadvantage: since it doesn't do everything foryou, there's a lot you have to do yourself. (#ctually, this is viewed by many as anadditional advantage: anything the language doesn't do for you, it doesn't dictateto you, either, so you're free to do that something however you want.)

    C is sometimes referred to as a $$high%level assembly language.'' ome eolethin that's an insult, but it's actually a deliberate and significant asect of thelanguage. "f you have rogrammed in assembly language, you'll robably find Cvery natural and comfortable (although if you continue to focus too heavily onmachine%level details, you'll robably end u with unnecessarily nonortable

    rograms). "f you haven't rogrammed in assembly language, you may befrustrated by C's lac of certain higher%level features. "n either case, you shouldunderstand why C was designed this way: so that seemingly%simleconstructions e!ressed in C would not e!and to arbitrarily e!ensive (in time orsace) machine language constructions when comiled. "f you write a C rogramsimly and succinctly, it is liely to result in a succinct, efficient machinelanguage e!ecutable. "f you find that the e!ecutable rogram resulting from a Crogram is not efficient, it's robably because of something silly you did, notbecause of something the comiler did behind your bac which you have nocontrol over. "n any case, there's no oint in comlaining about C's low%levelflavor: C is what it is.

    # rogramming language is a tool, and no tool can erform every tas unaided. "fyou're building a house, and "'m teaching you how to use a hammer, and you ashow to assemble rafters and trusses into gables, that's a legitimate uestion, butthe answer has fallen out of the realm of $$*ow do " use a hammer+'' and into$$*ow do " build a house+''. "n the same way, we'll see that C does not have built%in features to erform every function that we might ever need to do whilerogramming.

    #s mentioned above, C imoses relatively few built%in ways of doing things onthe rogrammer. ome common tass, such as maniulating strings, allocating

    memory, and doing inutoutut ("-), are erformed by calling on libraryfunctions. -ther tass which you might want to do, such as creating or listingdirectories, or interacting with a mouse, or dislaying windows or other user%interface elements, or doing color grahics, are not defined by the C language atall. ou can do these things from a C rogram, of course, but you will be callingon services which are eculiar to your rogramming environment (comiler,rocessor, and oerating system) and which are not defined by the C standard.

  • 8/12/2019 C Programming 001

    2/36

    ince this course is about ortable C rogramming, it will also be steering clearof facilities not rovided in all C environments.

    #nother asect of C that's worth mentioning here is that it is, to ut it bluntly, a bitdangerous. C does not, in general, try hard to rotect a rogrammer from

    mistaes. "f you write a iece of code which will (through some oversight ofyours) do something wildly different from what you intended it to do, u to andincluding deleting your data or trashing your dis, and if it is ossible for thecomiler to comile it, it generally will. ou won't get warnings of the form $$/oyou really mean to...+'' or $$#re you sure you really want to...+''. C is oftencomared to a shar nife: it can do a surgically recise 0ob on some e!actingtas you have in mind, but it can also do a surgically recise 0ob of cutting offyour finger. "t's u to you to use it carefully.

    1his asect of C is very widely critici2ed it is also used (0ustifiably) to argue thatC is not a good teaching language. C aficionados love this asect of C because it

    means that C does not try to rotect them from themselves: when they nowwhat they're doing, even if it's risy or obscure, they can do it. tudents of C hatethis asect of C because it often seems as if the language is some ind of aconsiracy secifically designed to lead them into booby tras and $$gotcha3''s.

    1his is another asect of the language which it's fairly ointless to comlainabout. "f you tae care and ay attention, you can avoid many of the itfalls.1hese notes will oint out many of the obvious (and not so obvious) troublesots.

    4.4 # 5irst 6!amle

    4.7 econd 6!amle

    4.8 9rogram tructure

    1.1 A First Example

    1his section corresonds to K&R ec. 4.4;

    1he best way to learn rogramming is to dive right in and start writing real

    rograms. 1his way, concets which would otherwise seem abstract maesense, and the ositive feedbac you get from getting even a small rogram towor gives you a great incentive to imrove it or write the ne!t one.

    /iving in with $$real'' rograms right away has another advantage, if onlyragmatic: if you're using a conventional comiler, you can't run a fragment of arogram and see what it does nothing will run until you have a comlete (if tinyor trivial) rogram. ou can't learn everything you'd need to write a comlete

    http://www.eskimo.com/~scs/cclass/notes/sx1a.htmlhttp://www.eskimo.com/~scs/cclass/notes/sx1b.htmlhttp://www.eskimo.com/~scs/cclass/notes/sx1c.htmlhttp://www.eskimo.com/~scs/cclass/notes/sx1a.htmlhttp://www.eskimo.com/~scs/cclass/notes/sx1b.htmlhttp://www.eskimo.com/~scs/cclass/notes/sx1c.html
  • 8/12/2019 C Programming 001

    3/36

    rogram all at once, so you'll have to tae some things $$on faith'' and arrotthem in your first rograms before you begin to understand them. (ou can'tlearn to rogram 0ust one e!ression or statement at a time any more than youcan learn to sea a foreign language one word at a time. "f all you now is ahandful of words, you can't actually say anything: you also need to now

    something about the language's word order and grammar and sentence structureand declension of articles and verbs.)

    include ?stdio.h@

    main()Arintf(B*ello, world3nB)return DE

    "f you have a C comiler, the first thing to do is figure out how to tye thisrogram in and comile it and run it and see where its outut went. ("f you don'thave a C comiler yet, the first thing to do is to find one.)

    1he first line is ractically boilerlate it will aear in almost all rograms wewrite. "t ass that some definitions having to do with the $$tandard "- Fibrary''be included in our rogram these definitions are needed if we are to call thelibrary function rintfcorrectly.

  • 8/12/2019 C Programming 001

    4/36

    1he second line says that we are defining a function named main. Gost of thetime, we can name our functions anything we want, but the function name mainissecial: it is the function that will be $$called'' first when our rogram startsrunning. 1he emty air of arentheses indicates that our mainfunction accetsno arguments, that is, there isn't any information which needs to be assed in

    when the function is called.

    1he braces Aand Esurround a list of statements in C. *ere, they surround the listof statements maing u the function main.

    1he line

    rintf(B*ello, world3nB)

    is the first statement in the rogram. "t ass that the function rintfbe called rintfis a library function which rints formatted outut. 1he arentheses surroundrintf's argument list: the information which is handed to it which it should act on.1he semicolon at the end of the line terminates the statement.

    (printf's name reflects the fact that C was first develoed when 1eletyes and

    other rinting terminals were still in widesread use. 1oday, of course, videodislays are far more common. printf's $$rints'' to the standard output, that is,

    to the default location for rogram outut to go. Howadays, that's almost alwaysa video screen or a window on that screen. "f you do have a rinter, you'lltyically have to do something e!tra to get a rogram to rint to it.)

    rintf's first (and, in this case, only) argument is the string which it should rint.1he string, enclosed in double uotes BB, consists of the words $$*ello, world3''followed by a secial seuence: n. "n strings, any two%character seuencebeginning with the bacslash reresents a single secial character. 1heseuence nreresents the $$new line'' character, which rints a carriage returnor line feed or whatever it taes to end one line of outut and move down to thene!t. (1his rogram only rints one line of outut, but it's still imortant toterminate it.)

    1he second line in the mainfunction is

    return D

    "n general, a function may return a value to its caller, and mainis no e!cetion.=hen mainreturns (that is, reaches its end and stos functioning), the rogram is

    at its end, and the return value from maintells the oerating system (or whateverinvoed the rogram that main is the main function of) whether it succeeded ornot.

  • 8/12/2019 C Programming 001

    5/36

    or how to invoe it, or what haened after (if+) it ran. 1he most e!erienced Crogrammers immediately go bac to this one, simle rogram whenever they'retrying out a new system or a new way of entering or building rograms or a newway of rinting outut from within rograms. #s Kernighan and Ritchie say,everything else is comaratively easy.

    *ow youcomile and run this (or any) rogram is a function of the comiler andoerating system you're using. 1he first ste is to tye it in, e!actly as shown thismay involve using a te!t editor to create a file containing the rogram te!t. ou'llhave to give the file a name, and all C comilers (that "'ve ever heard of) reuirethat files containing C source end with the e!tension .c. o you might lace therogram te!t in a file called hello.c.

    1he second ste is to comile the rogram. (trictly seaing, comilationconsists of two stes, comilation roer followed by lining, but we can overloothis distinction at first, esecially because the comiler often taes care of

    initiating the lining ste automatically.) -n many Ini! systems, the command tocomile a C rogram from a source file hello.cis

    cc %o hello hello.c

    ou would tye this command at the Ini! shell romt, and it reuests that the cc(C comiler) rogram be run, lacing its outut (i.e. the new e!ecutable rogramit creates) in the file hello, and taing its inut (i.e. the source code to becomiled) from the file hello.c.

    1he third ste is to run (e!ecute, invoe) the newly%built hellorogram. #gain on aIni! system, this is done simly by tying the rogram's name:

    hello

    /eending on how your system is set u (in articular, on whether the currentdirectory is searched for e!ecutables, based on the 9#1* variable), you mayhave to tye

    .hello

    to indicate that the hellorogram is in the current directory (as oosed to some$$bin'' directory full of e!ecutable rograms, elsewhere).

    ou may also have your choice of C comilers. -n many Ini! machines, the cccommand is an older comiler which does not recogni2e modern, #H" tandardC synta!. #n old comiler will accet the simle rograms we'll be starting with,

    but it will not accet most of our later rograms. "f you find yourself gettingbaffling comilation errors on rograms which you've tyed in e!actly as they'reshown, it robably indicates that you're using an older comiler. -n manymachines, another comiler called accor gccis available, and you'll want to use it,instead. (

  • 8/12/2019 C Programming 001

    6/36

    (-ne final caveat about Ini! systems: don't name your test rograms test,because there's already a standard command called test, and you and thecommand interreter will get badly confused if you try to relace the system's testcommand with your own, not least because your own almost certainly doessomething comletely different.)

    Inder G%/-, the comilation rocedure is uite similar. 1he name of thecommand you tye will deend on your comiler (e.g. cl for the Gicrosoft Ccomiler, tc or bcc for

  • 8/12/2019 C Programming 001

    7/36

  • 8/12/2019 C Programming 001

    8/36

    case, the letter dindicates that rintfis to e!ect an int, and to rint it in decimal.5inally, we see that rintfis in fact being called with another argument, for a totalof two, searated by commas. 1he second argument is the variable i, which is infact an int, as reuired by Md. 1he effect of all of this is that each time it is called,rintfwill rint a line containing the current value of the variable i:

    i is Di is 4i is 7...

    #fter several tris through the loo, i will eventually eual N. #fter that trithrough the loo, the third control e!ression i = i + 1will increment its value to

    4D. 1he condition i < 10is no longer true, so no more tris through the loo aretaen. "nstead, control flow 0ums down to the statement following the for loo,

    which is the return statement. 1he mainfunction returns, and the rogram isfinished.

    1.3 Program Structure

    =e'll have more to say later about rogram structure, but for now let's observe afew basics. # rogram consists of one or more functions it may also containglobal variables. (-ur two e!amle rograms so far have contained one functionaiece, and no global variables.) #t the to of a source file are tyically a fewboilerlate lines such as >include ?stdio.h@, followed by the definitions (i.e. code) forthe functions. ("t's also ossible to slit u the several functions maing u a

    larger rogram into several source files, as we'll see in a later chater.)

    6ach function is further comosed of declarationsand statements, in that order.=hen a seuence of statements should act as one (for e!amle, when theyshould all serve together as the body of a loo) they can be enclosed in braces(0ust as for the outer body of the entire function). 1he simlest ind of statementis an expression statement, which is an e!ression (resumably erformingsome useful oeration) followed by a semicolon. 6!ressions are furthercomosed of operators, objects(variables), and constants.

    C source code consists of several lexical elements. ome are words, such as for,

    return, main, and i, which are either keywords of the language (for, return) oridentifiers(names) we've chosen for our own functions and variables (main, i).1here are constants such as 4 and 4D which introduce new values into therogram. 1here are operatorssuch as , L, and @, which maniulate variablesand values. 1here are other unctuation characters (often called delimiters), suchas arentheses and suiggly braces AE, which indicate how the other elements ofthe rogram are groued. 5inally, all of the receding elements can be searatedby whitespace: saces, tabs, and the $$carriage returns'' between lines.

  • 8/12/2019 C Programming 001

    9/36

    1he source code for a C rogram is, for the most art, $$free form.'' 1his meansthat the comiler does not care how the code is arranged: how it is broen intolines, how the lines are indented, or whether whitesace is used between thingslie variable names and other unctuation. (Fines lie >include ?stdio.h@ are ane!cetion they must aear alone on their own lines, generally unbroen. -nly

    lines beginning with >are affected by this rule we'll see other e!amles later.)ou can use whitesace, indentation, and aroriate line breas to mae yourrograms more readable for yourself and other eole (even though the comilerdoesn't care). ou can lace e!lanatory commentsanywhere in your rogram%%any te!t between the characters Jand Jis ignored by the comiler. ("n fact, thecomiler retends that all it saw was whitesace.) 1hough comments are ignoredby the comiler, well%chosen comments can mae a rogram mucheasier toread (for its author, as well as for others).

    1he usage of whitesace is our first styleissue. "t's tyical to leave a blan linebetween different arts of the rogram, to leave a sace on either side of

    oerators such as L and , and to indentthe bodies of loos and other controlflow constructs. 1yically, we arrange the indentation so that the subsidiarystatements controlled by a loo statement (the $$loo body,'' such as the rintfcallin our second e!amle rogram) are all aligned with each other and laced onetab sto (or some consistent number of saces) to the right of the controllingstatement. 1his indentation (lie all whitesace) is not reuired by the comiler,but it maes rograms mucheasier to read. (*owever, it can also be misleading,if used incorrectly or in the face of inadvertent mistaes. 1he comiler will decidewhat $$the body of the loo'' is based on its own rules, not the indentation, so ifthe indentation does not match the comiler's interretation, confusion isinevitable.)

    1o drive home the oint that the comiler doesn't care about indentation, linebreas, or other whitesace, here are a few (e!treme) e!amles: 1he fragments

    for(i D i ? 4D i i L 4)rintf(BMdnB, i)

    andfor(i D i ? 4D i i L 4) rintf(BMdnB, i)

    andfor(iDi?4DiiL4)rintf(BMdnB,i)

    andfor(i D i ? 4D i i L 4)

    rintf(BMdnB, i)

    andfor ( i D i ? 4D i i L 4) rintf (BMdnB , i)

  • 8/12/2019 C Programming 001

    10/36

    andfor

    (iD i?4DiiL4)rintf(BMdnB, i)

    are all treated e!actly the same way by the comiler.

    ome rogrammers argue forever over the best set of $$rules'' for indentation andother asects of rogramming style, calling to mind the old hilosoher's debatesabout the number of angels that could dance on the head of a in. tyle issues(such as how a rogram is laid out) areimortant, but they're not something to betoo dogmatic about, and there are also other, deeer style issues besides merelayout and tyograhy. Kernighan and Ritchie tae a fairly moderate stance:

    #lthough C comilers do not care about how a rogram loos, roer indentationand sacing are critical in maing rograms easy for eole to read. =e

    recommend writing only one statement er line, and using blans aroundoerators to clarify grouing. 1he osition of braces is less imortant, althougheole hold assionate beliefs. =e have chosen one of several oular styles.9ic a style that suits you, then use it consistently.

    1here is some value in having a reasonably standard style (or a few standardstyles) for code layout. 9lease don't tae the above advice to $$ic a style thatsuits you'' as an invitation to invent your own brand%new style. "f (erhas afteryou've been rogramming in C for a while) you have secific ob0ections tosecific facets of e!isting styles, you're welcome to modify them, but if you don'thave any articular leanings, you're robably best off coying an e!isting style at

    first. ("f you want to lace your own stam of originality on the rograms that youwrite, there are better avenues for your creativity than inventing a bi2arre layoutyou might instead try to mae the logic easier to follow, or the user interfaceeasier to use, or the code freer of bugs.)

    Chapter 2: Basic ata !"pes and #perators

    1he type of a variable determines what inds of values it may tae on. #noperator comutes new values out of old ones. #n expression consists ofvariables, constants, and oerators combined to erform some useful

    comutation. "n this chater, we'll learn about C's basic tyes, how to writeconstants and declare variables of these tyes, and what the basic oerators are.

    #s Kernighan and Ritchie say, $$1he tye of an ob0ect determines the set ofvalues it can have and what oerations can be erformed on it.'' 1his is a fairlyformal, mathematical definition of what a tye is, but it is traditional (andmeaningful). 1here are several imlications to remember:

  • 8/12/2019 C Programming 001

    11/36

    1. 1he $$set of values'' is finite. C's int tye can not reresent all of theintegers its floattye can not reresent allfloating%oint numbers.

    7. =hen you're using an ob0ect (that is, a variable) of some tye, you mayhave to remember what values it can tae on and what oerations you canerform on it. 5or e!amle, there are several oerators which lay with the

    binary (bit%level) reresentation of integers, but these oerators are notmeaningful for and may not be alied to floating%oint oerands.8. =hen declaring a new variable and icing a tye for it, you have to ee

    in mind the values and oerations you'll be needing.

    "n other words, icing a tye for a variable is not some abstract academice!ercise it's closely connected to the way(s) you'll be using that variable.

    7.4 1yes

    7.7 Constants

    7.8 /eclarations

    7.O Pariable Hames

    7.Q #rithmetic -erators

    7. #ssignment -erators

    7.S 5unction Calls

    Read seuentially: revne!tuto

    1his age by teve ummit Coyright4NNQ, 4NN mail feedbac

    2.1 !"pes

    1his section corresonds to K&R ec. 7.7;

    1here are only a few basic data tyes in C. 1he first ones we'll be encounteringand using are:

    char a character

    int an integer, in the range %87,SS to 87,SS

    long int a larger integer (u to L%7,4OS,OT8,OS)

    float a floating%oint number

    double a floating%oint number, with more recision and erhas greater

    range than float

    http://www.eskimo.com/~scs/cclass/notes/sx2a.htmlhttp://www.eskimo.com/~scs/cclass/notes/sx2b.htmlhttp://www.eskimo.com/~scs/cclass/notes/sx2c.htmlhttp://www.eskimo.com/~scs/cclass/notes/sx2d.htmlhttp://www.eskimo.com/~scs/cclass/notes/sx2e.htmlhttp://www.eskimo.com/~scs/cclass/notes/sx2f.htmlhttp://www.eskimo.com/~scs/cclass/notes/sx2g.htmlhttp://www.eskimo.com/~scs/cclass/notes/sx1c.htmlhttp://www.eskimo.com/~scs/cclass/notes/sx2a.htmlhttp://www.eskimo.com/~scs/cclass/notes/top.htmlhttp://www.eskimo.com/~scs/cclass/notes/top.htmlhttp://www.eskimo.com/~scs/cclass/notes/top.htmlhttp://www.eskimo.com/~scs/http://www.eskimo.com/~scs/cclass/notes/copyright.htmlmailto:[email protected]://www.eskimo.com/~scs/cclass/notes/sx2a.htmlhttp://www.eskimo.com/~scs/cclass/notes/sx2b.htmlhttp://www.eskimo.com/~scs/cclass/notes/sx2c.htmlhttp://www.eskimo.com/~scs/cclass/notes/sx2d.htmlhttp://www.eskimo.com/~scs/cclass/notes/sx2e.htmlhttp://www.eskimo.com/~scs/cclass/notes/sx2f.htmlhttp://www.eskimo.com/~scs/cclass/notes/sx2g.htmlhttp://www.eskimo.com/~scs/cclass/notes/sx1c.htmlhttp://www.eskimo.com/~scs/cclass/notes/sx2a.htmlhttp://www.eskimo.com/~scs/cclass/notes/top.htmlhttp://www.eskimo.com/~scs/cclass/notes/top.htmlhttp://www.eskimo.com/~scs/http://www.eskimo.com/~scs/cclass/notes/copyright.htmlmailto:[email protected]
  • 8/12/2019 C Programming 001

    12/36

    "f you can loo at this list of basic tyes and say to yourself, $$-h, how simle,there are only a few tyes, " won't have to worry much about choosing amongthem,'' you'll have an easy time with declarations. (ome masochists wish thatthe tye system were more comlicated so that they could secify more thingsabout each variable, but those of us who would rather not have to secify these

    e!tra things each time are glad that we don't have to.)

    1he ranges listed above for tyes int and long intare the guaranteed minimumranges. -n some systems, either of these tyes (or, indeed, any C tye) may beable to hold larger values, but a rogram that deends on e!tended ranges willnot be as ortable. ome rogrammers become obsessed with nowing e!actlywhat the si2es of data ob0ects will be in various situations, and go on to writerograms which deend on these e!act si2es. /etermining or controlling the si2eof an ob0ect is occasionally imortant, but most of the time we can sideste si2eissues and let the comiler do most of the worrying.

    (5rom the ranges listed above, we can determine that tye intmust be at least 4bits, and that tye long intmust be at least 87 bits.

  • 8/12/2019 C Programming 001

    13/36

  • 8/12/2019 C Programming 001

    14/36

    B a double uote (e.g. in a string constant) a single bacslash

    5or e!amle, "he said \"hi\""is a string constant which contains two doubleuotes, and '\''is a character constant consisting of a (single) single uote.

    Hotice once again that the character constant 'A'is very different from the stringconstant "A".

    2.3 eclarations

    1his section corresonds to K&R ec. 7.O;

    "nformally, a variable(also called an object) is a lace you can store a value. othat you can refer to it unambiguously, a variable needs a name. ou can thin ofthe variables in your rogram as a set of bo!es or cubbyholes, each with a label

    giving its name you might imagine that storing a value $$in'' a variable consists ofwriting the value on a sli of aer and lacing it in the cubbyhole.

    # declarationtells the comiler the name and tye of a variable you'll be using inyour rogram. "n its simlest form, a declaration consists of the tye, the name ofthe variable, and a terminating semicolon:

    char cint ifloat f

    ou can also declare several variables of the same tye in one declaration,searating them with commas:

    int i4, i7

    Fater we'll see that declarations may also contain initializers, qualifiers andstorage classes, and that we can declare arrays, functions, pointers, and otherinds of data structures.

    1he lacement of declarations is significant. ou can't lace them 0ust anywhere(i.e. they cannot be intersersed with the other statements in your rogram).1hey must either be laced at the beginning of a function, or at the beginning of abrace%enclosed bloc of statements (which we'll learn about in the ne!t chater),or outside of any function. 5urthermore, the lacement of a declaration, as wellas its storage class, controls several things about its visibilityand lifetime, as we'llsee later.

    ou may wonder whyvariables must be declared before use. 1here are tworeasons:

  • 8/12/2019 C Programming 001

    15/36

    4. "t maes things somewhat easier on the comiler it nows right awaywhat ind of storage to allocate and what code to emit to store andmaniulate each variable it doesn't have to try to intuit the rogrammer'sintentions.

    7. "t forces a bit of useful disciline on the rogrammer: you cannot introduce

    variables willy%nilly you must thin about them enough to ic aroriatetyes for them. (1he comiler's error messages to you, telling you that youaarently forgot to declare a variable, are as often helful as they are anuisance: they're helful when they tell you that you misselled a variable,or forgot to thin about e!actly how you were going to use it.)

    #lthough there are a few laces where declarations can be omitted (in whichcase the comiler will assume an imlicit declaration), maing use of theseremoves the advantages of reason 7 above, so " recommend always declaringeverything e!licitly.

    Gost of the time, " recommend writing one declaration er line. 5or the most art,the comiler doesn't care what order declarations are in. ou can order thedeclarations alhabetically, or in the order that they're used, or to ut relateddeclarations ne!t to each other. Collecting all variables of the same tye togetheron one line essentially orders declarations by tye, which isn't a very useful order(it's only slightly more useful than random order).

    # declaration for a variable can also contain an initial value. 1his initializerconsists of an euals sign and an e!ression, which is usually a single constant:

    int i 4int i4 4D, i7 7D

    2.$ %aria&le 'ames

    1his section corresonds to K&R ec. 7.4;

    =ithin limits, you can give your variables and functions any names you want.1hese names (the formal term is $$identifiers'') consist of letters, numbers, andunderscores. 5or our uroses, names must begin with a letter. 1heoretically,names can be as long as you want, but e!tremely long ones get tedious to tyeafter a while, and the comiler is not reuired to ee trac of e!tremely long

    ones erfectly. (=hat this means is that if you were to name a variable, say,suercalafragalisticesialidocious, the comiler might get la2y and retend that you'dnamed it suercalafragalisticesialidocio, such that if you later misselled itsuercalafragalisticesialidociou2, the comiler wouldn't catch your mistae. Hor wouldthe comiler necessarily be able to tell the difference if for some erverse reasonyou deliberatelydeclared a second variable named suercalafragalisticesialidociou2.)

  • 8/12/2019 C Programming 001

    16/36

    1he caitali2ation of names in C is significant: the variable names variable,Pariable, and P#R"#

  • 8/12/2019 C Programming 001

    17/36

    rogramming than it is in mathematics. Hot all C oerators grou from left toright a few grou from right to left.)

    =henever the default recedence or associativity doesn't give you the grouingyou want, you can always use e!licit arentheses. 5or e!amle, if you wanted

    to add 4 to 7 and then multily the result by 8, you could write (4 L 7) J 8.

  • 8/12/2019 C Programming 001

    18/36

    #ll of these oerators $$grou'' from left to right, which means that when two ormore of them have the same recedence and articiate ne!t to each other in ane!ression, the evaluation concetually roceeds from left to right. 5or e!amle,4 % 7 % 8is euivalent to (4 % 7) % 8and gives %O, not L7. ($$Wrouing'' is sometimescalled associativity, although the term is used somewhat differently in

    rogramming than it is in mathematics. Hot all C oerators grou from left toright a few grou from right to left.)

    =henever the default recedence or associativity doesn't give you the grouingyou want, you can always use e!licit arentheses. 5or e!amle, if you wantedto add 4 to 7 and then multily the result by 8, you could write (4 L 7) J 8.

  • 8/12/2019 C Programming 001

    19/36

    "t's usually a matter of style whether you initiali2e a variable with an initiali2er inits declaration or with an assignment e!ression near where you first use it. 1hatis, there's no articular difference between

    int a 4D

    andint a

    J later... J

    a 4D

    2.* Function Calls

    =e'll have much more to say about functions in a later chater, but for now let's0ust loo at how they're called. (1o review: what a function isis a iece of code,written by you or by someone else, which erforms some useful,

    comartmentali2able tas.) ou call a function by mentioning its name followedby a air of arentheses. "f the function taes any arguments, you lace thearguments between the arentheses, searated by commas. 1hese are allfunction calls:

    rintf(B*ello, world3nB)rintf(BMdnB, i)srt(4OO.)getchar()

    1he arguments to a function can be arbitrary e!ressions. 1herefore, you don'thave to say things lie

    int sum a L b L crintf(Bsum MdnB, sum)

    if you don't want to you can instead collase it torintf(Bsum MdnB, a L b L c)

    Gany functions return values, and when they do, you can embed calls to thesefunctions within larger e!ressions:

    c srt(a J a L b J b)! r J cos(theta)i f4(f7(0))

    1he first e!ression suares aand b, comutes the suare root of the sum of the

    suares, and assigns the result to c. ("n other words, it comutes a * a + b * b,asses that number to the sqrtfunction, and assigns sqrt's return value to c.)

    1he second e!ression asses the value of the variabletheta

    to thecos

    (cosine)function, multilies the result by r, and assigns the result to x. 1he third

    e!ression asses the value of the variable to the function f!, asses thereturn value of f!immediately to the function f1, and finally assigns f1's return

    value to the variable i.

  • 8/12/2019 C Programming 001

    20/36

    Chapter 3: Statements and Control Flo+

    tatements are the $$stes'' of a rogram. Gost statements comute and assignvalues or call functions, but we will eventually meet several other inds ofstatements as well.

  • 8/12/2019 C Programming 001

    21/36

    statements are followed by semicolons. 1he semicolon is also used for a fewother things in C we've already seen that it terminates declarations, too.)

    6!ression statements do all of the real wor in a C rogram. =henever youneed to comute new values for variables, you'll tyically use e!ression

    statements (and they'll tyically contain assignment oerators). =henever youwant your rogram to do something visible, in the real world, you'll tyically call afunction (as art of an e!ression statement). =e've already seen the most basice!amle: calling the function rintfto rint te!t to the screen.

  • 8/12/2019 C Programming 001

    22/36

    only be looing at e!ressions (and, therefore, statements) which do one well%defined thing at a time.

    3.2 i,Statements

    1his section corresonds to K&R ec. 8.7;

    1he simlest way to modify the control flow of a rogram is with an ifstatement,which in its simlest form loos lie this:

    if(! @ ma!)ma! !

    6ven if you didn't now any C, it would robably be retty obvious that what

    haens here is that if !is greater than ma!, !gets assigned to ma!. (=e'd usecode lie this to ee trac of the ma!imum value of !we'd seen%%for each new !,we'd comare it to the old ma!imum value ma!, and if the new value was greater,we'd udate ma!.)

    Gore generally, we can say that the synta! of an ifstatement is:

    if( expression)statement

    where expressionis any e!ression and statementis any statement.

    =hat if you have a series of statements, all of which should be e!ecuted togetheror not at all deending on whether some condition is true+ 1he answer is thatyou enclose them in braces:

    if( expression)Astatement1statementstatement!E

    #s a general rule, anywhere the synta! of C calls for a statement, you may writea series of statements enclosed by braces. (ou do not need to, and should not,

    ut a semicolon after the closing brace, because the series of statementsenclosed by braces is not itself a simle e!ression statement.)

    #n if statement may also otionally contain a second statement, the $$elseclause,'' which is to be e!ecuted if the condition is not met. *ere is an e!amle:

    if(n @ D)average sum n

    else A

  • 8/12/2019 C Programming 001

    23/36

    rintf(Bcan't comute averagenB)average DE

    1he first statement or bloc of statements is e!ecuted if the condition istrue, andthe second statement or bloc of statements (following the eyword else) ise!ecuted if the condition is not true. "n this e!amle, we can comute a

    meaningful average only if nis greater than D otherwise, we rint a messagesaying that we cannot comute the average. 1he general synta! of an ifstatement is therefore

    if( expression)statement1

    elsestatement

    (where both statement1 and statement may be lists ofstatements enclosed in braces).

    "t's also ossible to nest one ifstatement inside another. (5or that matter, it's ingeneral ossible to nest any ind of statement or control flow construct withinanother.) 5or e!amle, here is a little iece of code which decides roughly whichuadrant of the comass you're waling into, based on an ! value which isositive if you're waling east, and a yvalue which is ositive if you're walingnorth:

    if(! @ D)Aif(y @ D)

    rintf(BHortheast.nB)else rintf(Boutheast.nB)E

    else A

    if(y @ D)rintf(BHorthwest.nB)

    else rintf(Bouthwest.nB)E

    =hen you have one ifstatement (or loo) nested inside another, it's a very goodidea to use e!licit braces AE, as shown, to mae it clear (both to you and to thecomiler) how they're nested and which elsegoes with which if. "t's also a goodidea to indent the various levels, also as shown, to mae the code more readableto humans. =hy do both+ ou use indentation to mae the code visually morereadable to yourself and other humans, but the comiler doesn't ay attention tothe indentation (since all whitesace is essentially euivalent and is essentiallyignored). 1herefore, you also have to mae sure that the unctuation is right.

    *ere is an e!amle of another common arrangement of ifand else. uose wehave a variable gradecontaining a student's numeric grade, and we want to rintout the corresonding letter grade. *ere is code that would do the 0ob:

    if(grade @ ND)rintf(B#B)

    else if(grade @ TD)

  • 8/12/2019 C Programming 001

    24/36

    rintf(B

  • 8/12/2019 C Programming 001

    25/36

    #n ifstatement lie

    if(! @ ma!)ma! !

    is erhas decetively simle. Concetually, we say that it checs whether thecondition ! @ ma!is $$true'' or $$false''. 1he mechanics underlying C's concetionof $$true'' and $$false,'' however, deserve some e!lanation. =e need tounderstand how true and false values are reresented, and how they areinterreted by statements lie if.

    #s far as C is concerned, a truefalse condition can be reresented as an integer.(#n integer can reresent many values here we care about only two values:$$true'' and $$false.'' 1he study of mathematics involving only two values is called

  • 8/12/2019 C Programming 001

    26/36

    which tae truefalse values as oerands and comute new truefalse values.1he three

  • 8/12/2019 C Programming 001

    27/36

    evaluating an ifstatement, or anywhere else where it needs a truefalse value) iswhether the e!ression evaluates to D or non2ero. 5or e!amle, if you have avariable !, and you want to do something if !is non2ero, it's ossible to write

    if(!)statement

    and the statement will be e!ecuted if !is non2ero (since non2ero means $$true'').

    1his ossibility (that the controlling e!ression of an ifstatement doesn't have to$$loo lie'' a

  • 8/12/2019 C Programming 001

    28/36

    Foos generally consist of two arts: one or more control expressionswhich (notsurrisingly) control the e!ecution of the loo, and the body, which is thestatement or set of statements which is e!ecuted over and over.

    1he most basic loop in C is the while loo. # while loo has one control

    e!ression, and e!ecutes as long as that e!ression is true. 1his e!amlereeatedly doubles the number 7 (7, O, T, 4, ...) and rints the resulting numbersas long as they are less than 4DDD:

    int ! 7

    while(! ? 4DDD)Arintf(BMdnB, !)! ! J 7E

    (-nce again, we've used braces AEto enclose the grou of statements which areto be e!ecuted together as the body of the loo.)

    1he general synta! of a whileloo is

    while( expression)statement

    # while loo starts out lie an ifstatement: if the condition e!ressed by theexpression is true, the statement is e!ecuted. *owever, after e!ecuting thestatement, the condition is tested again, and if it's still true, the statement ise!ecuted again. (9resumably, the condition deends on some value which ischanged in the body of the loo.) #s long as the condition remains true, the bodyof the loo is e!ecuted over and over again. ("f the condition is false right at the

    start, the body of the loo is not e!ecuted at all.)

    #s another e!amle, if you wanted to rint a number of blan lines, with thevariable nholding the number of blan lines to be rinted, you might use codelie this:

    while(n @ D)Arintf(BnB)n n % 4E

    #fter the loo finishes (when control $$falls out'' of it, due to the condition being

    false), nwill have the value D.

    ou use a hileloo when you have a statement or grou of statements which

    may have to be e!ecuted a number of times to comlete their tas. 1hecontrolling e!ression reresents the condition $$the loo is not done'' or $$there'smore wor to do.'' #s long as the e!ression is true, the body of the loo ise!ecuted resumably, it maes at least some rogress at its tas. =hen thee!ression becomes false, the tas is done, and the rest of the rogram (beyond

  • 8/12/2019 C Programming 001

    29/36

    the loo) can roceed. =hen we thin about a loo in this way, we can seen anadditional imortant roerty: if the e!ression evaluates to $$false'' before thevery first tri through the loo, we mae zero tris through the loo. "n otherwords, if the tas is already done (if there's no wor to do) the body of the loo isnot e!ecuted at all. ("t's always a good idea to thin about the $$boundary

    conditions'' in a iece of code, and to mae sure that the code will wor correctlywhen there is no wor to do, or when there is a trivial tas to do, such as sortingan array of one number. 6!erience has shown that bugs at boundary conditionsare uite common.)

    3.( ,or-oops

    1his section corresonds to the other half of K&R ec. 8.Q;

    -ur second loo, which we've seen at least one e!amle of already, is the for

    loo. 1he first one we saw was:

    for (i D i ? 4D i i L 4)rintf(Bi is MdnB, i)

    Gore generally, the synta! of a forloo isfor( expr1 expr expr!)

    statement

    (*ere we see that the for loo has three control e!ressions. #s always, thestatementcan be a brace%enclosed bloc.)

    Gany loos are set u to cause some variable to ste through a range of values,

    or, more generally, to set u an initial condition and then modify some value toerform each succeeding loo as long as some condition is true. 1he threee!ressions in a forloo encasulate these conditions: expr1sets uthe initial condition, exprtests whether another tri through the looshould be taen, and expr!increments or udates things after eachtri through the loo and rior to the ne!t one. "n our first e!amle, we had i Das expr1, i ? 4Das expr, i i L 4as expr!, andthe call to rintfas statement, the body of the loo. o the loo began by setting ito D, roceeded as long as iwas less than 4D, rinted out i's value during eachtri through the loo, and added 4 to ibetween each tri through the loo.

    =hen the comiler sees a for loo, first, expr1is evaluated. 1hen,expris evaluated, and if it is true, the body of the loo (statement)

    is e!ecuted. 1hen, expr! is evaluated to go to the ne!t ste, andexpris evaluated again, to see if there isa ne!t ste. /uring the

    e!ecution of a forloo, the seuence is:

    expr1

    expr

    statement

  • 8/12/2019 C Programming 001

    30/36

    expr!

    expr

    statementexpr!...expr

    statementexpr!

    expr

    1he first thing e!ecuted is expr1. expr! is evaluated aftereverytri through the loo. 1he last thing e!ecuted is always expr,because when exprevaluates false, the loo e!its.

    #ll three e!ressions of a forloo are otional. "f you leave out expr1,there simly is no initiali2ation ste, and the variable(s) used with the loo hadbetter have been initiali2ed already. "f you leave out expr, there is notest, and the default for the forloo is that another tri through the loo should betaen (such that unless you brea out of it some other way, the loo runsforever). "f you leave out expr!, there is no increment ste.

    1he semicolons searate the three controlling e!ressions of a forloo. (1hesesemicolons, by the way, have nothing to do with statement terminators.) "f youleave out one or more of the e!ressions, the semicolons remain. 1herefore, oneway of writing a deliberately infinite loo in C is

    for()...

    "t's useful to comare C's for loo to the euivalent loos in other comuter

    languages you might now. 1he C loo

    for(i ! i ? y i i L 2)

    is roughly euivalent to:for " Y to ste Z #"$%&'(

    do 4D i!,y,2 #)*+,+$-(

    for i : ! to y #.ascal(

    "n C (unlie 5-R1R#H), if the test condition is false before the first tri throughthe loo, the loo won't be traversed at all. "n C (unlie 9ascal), a loo controlvariable (in this case, i) is guaranteed to retain its final value after the loo

    comletes, and it is also legal to modify the control variable within the loo, if youreally want to. (=hen the loo terminates due to the test condition turning false,the value of the control variable after the loo will be the first value for which thecondition failed, not the last value for which it succeeded.)

    "t's also worth noting that a forloo can be used in more general ways than thesimle, iterative e!amles we've seen so far. 1he $$control variable'' of a forloodoes not have to be an integer, and it does not have to be incremented by an

  • 8/12/2019 C Programming 001

    31/36

    additive increment. "t could be $$incremented'' by a multilicative factor (4, 7, O, T,...) if that was what you needed, or it could be a floating%oint variable, or it couldbe another tye of variable which we haven't met yet which would ste, not overnumeric values, but over the elements of an array or other data structure. trictlyseaing, a forloo doesn't have to have a $$control variable'' at all the three

    e!ressions can be anything, although the loo will mae the most sense if theyare related and together form the e!ected initiali2e, test, increment seuence.

    1he owers%of%two e!amle of the revious section does fit this attern, so wecould rewrite it lie this:

    int !

    for(! 7 ! ? 4DDD ! ! J 7)rintf(BMdnB, !)

    1here is no earth%shaing or fundamental difference between the while and for

    loos. "n fact, given the general forloo

    for(expr1 expr expr!)statement

    you could usually rewrite it as a while loo, moving the initiali2e and incremente!ressions to statements before and within the loo:

    expr1while(expr)

    Astatementexpr!E

    imilarly, given the general whileloowhile(expr)statement

    you could rewrite it as a forloo:for( expr )

    statement

    #nother contrast between the for and while loos is that although the teste!ression (expr) is otional in a forloo, it is reuired in a whileloo."f you leave out the controlling e!ression of a while loo, the comiler willcomlain about a synta! error. (1o write a deliberately infinite whileloo, you haveto suly an e!ression which is always non2ero. 1he most obvious one would

    simly be while(4).)

    "f it's ossible to rewrite a forloo as a hileloo and vice versa, why do theyboth e!ist+ =hich one should you choose+ "n general, when you choose a for

    loo, its three e!ressions should all maniulate the same variable or datastructure, using the initiali2e, test, increment attern. "f they don't maniulate thesame variable or don't follow that attern, wedging them into a for loo buys

    nothing and a hileloo would robably be clearer. (1he reason that one loo or

  • 8/12/2019 C Programming 001

    32/36

    the other can be clearer is simly that, when you see a forloo, you expectto

    see an idiomatic initiali2etestincrement of a single variable, and if the for loo

    you're looing at doesn't end u matching that attern, you've been momentarilymisled.)

    3.) &reaand continue

    1his section corresonds to K&R ec. 8.S;

    ometimes, due to an e!cetional condition, you need to 0um out of a looearly, that is, before the main controlling e!ression of the loo causes it toterminate normally. -ther times, in an elaborate loo, you may want to 0um bacto the to of the loo (to test the controlling e!ression again, and erhas begina new tri through the loo) without laying out all the stes of the current loo.1he breaand continuestatements allow you to do these two things. (1hey are, infact, essentially restricted forms of goto.)

    1o ut everything we've seen in this chater together, as well as demonstrate theuse of the breastatement, here is a rogram for rinting rime numbers between4 and 4DD:

    >include ?stdio.h@>include ?math.h@

    main()Aint i, 0

    rintf(BMdnB, 7)

    for(i 8 i ? 4DD i i L 4)Afor(0 7 0 ? i 0 0 L 4)

    Aif(i M 0 D)

    breaif(0 @ srt(i))

    Arintf(BMdnB, i)brea

    EE

    E

    return DE

    1he outer loo stes the variable ithrough the numbers from 8 to 4DD the codetests to see if each number has any divisors other than 4 and itself. 1he trialdivisor0loos from 7 u to i.0is a divisor of iif the remainder of idivided by0is D,

  • 8/12/2019 C Programming 001

    33/36

    so the code uses C's $$remainder'' or $$modulus'' oerator Mto mae this test.(Remember that i M 0gives the remainder when iis divided by0.)

    "f the rogram finds a divisor, it uses breato brea out of the inner loo, withoutrinting anything.

  • 8/12/2019 C Programming 001

    34/36

    Hotice that the subscrited array references (i.e. e!ressions such as aD; anda4;) can aear on either side of the assignment oerator.

    1he subscrit does not have to be a constant lie Dor 4 it can be any integrale!ression. 5or e!amle, it's common to loo over all elements of an array:

    int i

    for(i D i ? 4D i i L 4)ai; D

    1his loo sets all ten elements of the array ato D.

    #rrays are a real convenience for many roblems, but there is not a lot that C willdo with them for you automatically. "n articular, you can neither set all elementsof an array at once nor assign one array to another both of the assignments

    a D J =R-HW J

    and int b4D;b a J =R-HW J

    are illegal.

    1o set all of the elements of an array to some value, you must do so one by one,as in the loo e!amle above. 1o coy the contents of one array to another, youmust again do so one by one:

    int b4D;

    for(i D i ? 4D i i L 4)

    bi; ai;Remember that for an array declared

    int a4D;

    there is no element a4D; the tomost element is aN;. 1his is one reason that2ero%based loos are also common in C. Hote that the forloo

    for(i D i ? 4D i i L 4)...

    does 0ust what you want in this case: it starts at D, the number 4D suggests(correctly) that it goes through 4D iterations, but the less%than comarison meansthat the last tri through the loo has iset to N. (1he comarison i ? Nwould alsowor, but it would be less clear and therefore oorer style.)

    "n the little e!amles so far, we've always looed over all 4D elements of thesamle array a. "t's common, however, to use an array that's bigger thannecessarily needed, and to use a second variable to ee trac of how manyelements of the array are currently in use. 5or e!amle, we might have aninteger variable

    int na J number of elements of a; in use J

  • 8/12/2019 C Programming 001

    35/36

    1hen, when we wanted to do something with a(such as rint it out), the loowould run from D to na, not 4D (or whatever a's si2e was):

    for(i D i ? na i i L 4)rintf(BMdnB, ai;)

    Haturally, we would have to ensure ensure that na's value was always less thanor eual to the number of elements actually declared in a.

    #rrays are not limited to tye int you can have arrays of char or doubleor anyother tye.

    *ere is a slightly larger e!amle of the use of arrays. uose we want toinvestigate the behavior of rolling a air of dice. 1he total roll can be anywherefrom 7 to 47, and we want to count how often each roll comes u. =e will use anarray to ee trac of the counts: a7;will count how many times we've rolled 7,etc.

    =e'll simulate the roll of a die by calling C's random number generation function,rand(). 6ach time you call rand(), it returns a different, seudo%random integer. 1hevalues that rand()returns tyically san a large range, so we'll use C's modulus(or $$remainder'') oerator Mto roduce random numbers in the range we want.1he e!ression rand() M roduces random numbers in the range D to Q, andrand() M L 4roduces random numbers in the range 4 to .

    *ere is the rogram:

    >include ?stdio.h@>include ?stdlib.h@

    main()Aint iint d4, d7int a48; J uses 7..47; J

    for(i 7 i ? 47 i i L 4)ai; D

    for(i D i ? 4DD i i L 4)Ad4 rand() M L 4d7 rand() M L 4ad4 L d7; ad4 L d7; L 4E

    for(i 7 i ? 47 i i L 4)rintf(BMd: MdnB, i, ai;)

    return DE

    =e include the header ?stdlib.h@because it contains the necessary declarationsfor the rand()function. =e declare the array of si2e 48 so that its highest element

  • 8/12/2019 C Programming 001

    36/36

    will be a47;. (=e're wasting aD;and a4; this is no great loss.) 1he variables d4and d7contain the rolls of the two individual dice we add them together to decidewhich cell of the array to increment, in the line

    ad4 L d7; ad4 L d7; L 4

    #fter 4DD rolls, we rint the array out. 1yically (as cras layers well now), we'llsee mostly S's, and relatively few 7's and 47's.

    (