C IN 21 DAYS

Embed Size (px)

Citation preview

  • 8/11/2019 C IN 21 DAYS

    1/23

    Welcome to Sams' Teach Yourself C in 21 Days!This chapter starts you toward becoming

    a proficient C programmer. Today you will learn

    Why C is the best choice among programming languages

    The steps in the program development cycle

    How to write, compile, and run your first C program

    About error messages generated by the compiler and linker

    A Brief History of the C Language

    You might be wondering about the origin of the C language and where it got its name. Cwas created by ennis !itchie at the "ell Telephone #aboratories in $%&'. The language

    wasn(t created for the fun of it, but for a specific purpose) to design the *+- operating

    system which is used on many computers/. 0rom the beginning, C was intended to beuseful11to allow busy programmers to get things done.

    "ecause C is such a powerful and fle2ible language, its use 3uickly spread beyond "ell

    #abs. 4rogrammers everywhere began using it to write all sorts of programs. 5oon,however, different organi6ations began utili6ing their own versions of C, and subtledifferences between implementations started to cause programmers headaches. n

    response to this problem, the American +ational 5tandards nstitute A+5/ formed a

    committee in $%78 to establish a standard definition of C, which became known as A+55tandard C. With few e2ceptions, every modern C compiler has the ability to adhere to

    this standard.

    +ow, what about the name9 The C language is so named because its predecessor was

    called ". The " language was developed by :en Thompson of "ell #abs. You should beable to guess why it was called ".

    Why Use C?

    n today(s world of computer programming, there are many high1level languages to

    choose from, such as C, 4ascal, "A5C, and ;ava. These are all e2cellent languagessuited for most programming tasks.

  • 8/11/2019 C IN 21 DAYS

    2/23

    C is a language of few words, containing only a handful of terms, called

    keywords,which serve as the base on which the language(s functionality is built.

    You might think that a language with more keywords sometimes called reseredwords/ would be more powerful. This isn(t true. As you program with C, you will

    find that it can be programmed to do any task.

    C is modular. C code can and should/ be written in routines calledfunctions.These functions can be reused in other applications or programs. "y passingpieces of information to the functions, you can create useful, reusable code.

    As these features show, C is an e2cellent choice for your first programming language.

    What about C@@9 You might have heard about C@@ and the programming techni3uecalled obect"oriented #ro$rammin$. 4erhaps you(re wondering what the differences are

    between C and C@@ and whether you should be teaching yourself C@@ instead of C.

    +ot to worry C@@ is a superset of C, which means that C@@ contains everything C does,

    plus new additions for ob=ect1oriented programming. f you do go on to learn C@@,

    almost everything you learn about C will still apply to the C@@ superset. n learning C,you are not only learning one of today(s most powerful and popular programming

    languages, but you are also preparing yourself for ob=ect1oriented programming.

    Another language that has gotten lots of attention is ;ava. ;ava, like C@@, is based on C.f later you decide to learn ;ava, you will find that almost everything you learned about C

    can be applied.

    Preparing to Program

    You should take certain steps when you(re solving a problem. 0irst, you must define the

    problem. f you don(t know what the problem is, you can(t find a solution Bnce youknow what the problem is, you can devise a plan to fi2 it. Bnce you have a plan, you can

    usually implement it. Bnce the plan is implemented, you must test the results to seewhether the problem is solved. This same logic can be applied to many other areas,

    including programming.

    When creating a program in C or for that matter, a computer program in any language/,

    you should follow a similar se3uence of steps)

    1. etermine the ob=ectives/ of the program.

    2. etermine the methods you want to use in writing the program.

    3. Create the program to solve the problem.4. !un the program to see the results.

    An e2ample of an ob=ective see step $/ might be to write a word processor or databaseprogram. A much simpler ob=ective is to display your name on the screen. f you didn(t

    have an ob=ective, you wouldn(t be writing a program, so you already have the first step

    done.

  • 8/11/2019 C IN 21 DAYS

    3/23

    The second step is to determine the method you want to use to write the program. o you

    need a computer program to solve the problem9 What information needs to be tracked9

    What formulas will be used9 uring this step, you should try to determine what you needto know and in what order the solution should be implemented.

    As an e2ample, assume that someone asks you to write a program to determine the areainside a circle. 5tep $ is complete, because you know your ob=ective) determine the area

    inside a circle. 5tep ' is to determine what you need to know to ascertain the area. n thise2ample, assume that the user of the program will provide the radius of the circle.

    :nowing this, you can apply the formula pr'to obtain the answer. +ow you have the

    pieces you need, so you can continue to steps 8 and , which are called the 4rogramevelopment Cycle.

    The Program e!e"opment Cy#"e

    The 4rogram evelopment Cycle has its own steps. n the first step, you use an editor to

    create a disk file containing your source code. n the second step, you compile the sourcecode to create an ob=ect file. n the third step, you link the compiled code to create an

    e2ecutable file. The fourth step is to run the program to see whether it works as originally

    planned.

    Creating the $our#e Co%e

    Source codeis a series of statements or commands that are used to instruct the computer

    to perform your desired tasks. As mentioned, the first step in the 4rogram evelopmentCycle is to enter source code into an editor. 0or e2ample, here is a line of C source code)

    printf("Hello, Mom!");

    This statement instructs the computer to display the message Hello, >om on1screen.

    0or now, don(t worry about how this statement works./

    Using an &%itor

    >ost compilers come with a built1in editor that can be used to enter source codeDhowever, some don(t. Consult your compiler manuals to see whether your compiler came

    with an editor. f it didn(t, many alternative editors are available.

    >ost computer systems include a program that can be used as an editor. f you(re using a*+- system, you can use such editors as ed, e2, edit, emacs, or vi. f you(re using>icrosoft Windows, +otepad is available. f you(re using >5EB5 F.G or later, you can

    use

  • 8/11/2019 C IN 21 DAYS

    4/23

    >ost word processors use special codes to format their documents. These codes can(t be

    read correctly by other programs. The American 5tandard Code for nformation

    nterchange A5C/ has specified a standard te2t format that nearly any program,including C, can use. >any word processors, such as Word4erfect, Ami4ro, Word,

    Word4ad, and Word5tar, are capable of saving source files in A5C form as a te2t file

    rather than a document file/. When you want to save a word processor(s file as an A5Cfile, select the A5C or te2t option when saving.

    f none of these editors is what you want to use, you can always buy a different editor.

    There are packages, both commercial and shareware, that have been designed specifically

    for entering source code.

    '(T&)To find alternative editors, you can check your local computer store or computer

    mail1order catalogs. Another place to look is in the ads in computer programming

    maga6ines.

    When you save a source file, you must give it a name. The name should describe what the

    program does. n addition, when you save C program source files, give the file a .C

    e2tension. Although you could give your source file any name and e2tension, .C isrecogni6ed as the appropriate e2tension to use.

    Compi"ing the $our#e Co%e

    Although you might be able to understand C source code at least, after reading this book

    you will be able to/, your computer can(t. A computer re3uires digital, or binary,

    instructions in what is called machine lan$ua$e. "efore your C program can run on acomputer, it must be translated from source code to machine language. This translation,the second step in program development, is performed by a program called a com#iler.

    The compiler takes your source code file as input and produces a disk file containing the

    machine language instructions that correspond to your source code statements. Themachine language instructions created by the compiler are called obect code,and the

    disk file containing them is called an obect file.

    '(T&)This book covers A+5 5tandard C. This means that it doesn(t matter which Ccompiler you use, as long as it follows the A+5 5tandard.

  • 8/11/2019 C IN 21 DAYS

    5/23

    >icrosoft C cl radius.c

    "orland(s Turbo C tcc radius.c

    "orland C bcc radius.c

    Iortec C 6tc radius.c

    To compile !A*5.C on a *+- machine, use the following command)

    cc radius.c

    Consult the compiler manual to determine the e2act command for your compiler.

    f you(re using a graphical development environment, compiling is even simpler. n mostgraphical environments, you can compile a program listing by selecting the compile icon

    or selecting something from a menu. Bnce the code is compiled, selecting the run icon or

    selecting something from a menu will e2ecute the program. You should check your

    compiler(s manuals for specifics on compiling and running a program.

    After you compile, you have an ob=ect file. f you look at a list of the files in the directory

    or folder in which you compiled, you should find a file that has the same name as your

    source file, but with an .B"; rather than a .C/ e2tension. The .B"; e2tension is

    recogni6ed as an ob=ect file and is used by the linker. Bn *+- systems, the compilercreates ob=ect files with an e2tension of .B instead of .B";.

    Lin*ing to Create an &+e#uta,"e -i"e

    Bne more step is re3uired before you can run your program. 4art of the C language is a

    function library that contains obect codecode that has already been compiled/ forpredefined functions. A#redefined functioncontains C code that has already been written

    and is supplied in a ready1to1use form with your compiler package.

    The printf/ function used in the previous e2ample is a library function. These library

    functions perform fre3uently needed tasks, such as displaying information on1screen and

    reading data from disk files. f your program uses any of these functions and hardly a

    program e2ists that doesn(t use at least one/, the ob=ect file produced when your sourcecode was compiled must be combined with ob=ect code from the function library to create

    the final e2ecutable program. %&ecutablemeans that the program can be run, or

    e2ecuted, on your computer./ This process is called linkin$,and it(s performed by a

    program called you guessed it/ a linker.

    0igure $.$ shows the progression from source code to ob=ect code to e2ecutable program.

    -igure 1.1.The C source code that you write is conerted to obect code by the com#iler

    and then to an e&ecutable file by the linker

    Comp"eting the e!e"opment Cy#"e

    http://popup%28%2701tyc01.gif%27%29/http://popup%28%2701tyc01.gif%27%29/
  • 8/11/2019 C IN 21 DAYS

    6/23

    Bnce your program is compiled and linked to create an e2ecutable file, you can run it by

    entering its name at the system prompt or =ust like you would run any other program. f

    you run the program and receive results different from what you thought you would, youneed to go back to the first step. You must identify what caused the problem and correct it

    in the source code. When you make a change to the source code, you need to recompile

    and relink the program to create a corrected version of the e2ecutable file. You keepfollowing this cycle until you get the program to e2ecute e2actly as you intended.

    Bne final note on compiling and linking) Although compiling and linking are mentioned

    as two separate steps, many compilers, such as the B5 compilers mentioned earlier, do

    both as one step. !egardless of the method by which compiling and linking areaccomplished, understand that these two processes, even when done with one command,

    are two separate actions.

    The C e!e"opment Cy#"e

    5tep$

    *se an editor to write your source code. "y tradition, C source code files have thee2tension .C for e2ample, >Y4!BJ.C, ATA"A5

  • 8/11/2019 C IN 21 DAYS

    7/23

    This demonstration uses a program named H

  • 8/11/2019 C IN 21 DAYS

    8/23

    . Jo back to step ' if this or any other error message is displayed. Bpen the

    H

  • 8/11/2019 C IN 21 DAYS

    9/23

    #ooking at this line, you can see that it has three parts)

    hello.c The name of the file where the error was found

    / ) The line number where the error was found

  • 8/11/2019 C IN 21 DAYS

    10/23

    make of the word Hello, because it is no longer enclosed in 3uotes. However, what about

    the other four errors that are reported9 These errors, the meaning of which you don(t need

    to worry about now, illustrate the fact that a single error in a C program can sometimescause multiple error messages.

    The lesson to learn from all this is as follows) f the compiler reports multiple errors, andyou can find only one, go ahead and fi2 that error and recompile. You might find that

    your single correction is all that(s needed, and the program will compile without errors.

    Lin*er &rror 5essages

    #inker errors are relatively rare and usually result from misspelling the name of a C

    library function. n this case, you get an

  • 8/11/2019 C IN 21 DAYS

    11/23

    6 After 8 #reate an e+e#uta,"e fi"e9 %o 8 nee% to *eep the sour#e fi"e :.C; or

    o,

    1. Jive three reasons why C is the best choice of programming language.2. What does the compiler do9

    3. What are the steps in the program development cycle9

    4. What command do you need to enter in order to compile a program called

    4!BJ!A>$.C with your compiler9

    /. oes your compiler do both the linking and compiling with =ust one command,

    or do you have to enter separate commands9

    0. What e2tension should you use for your C source files9

  • 8/11/2019 C IN 21 DAYS

    12/23

    . s 0#

  • 8/11/2019 C IN 21 DAYS

    13/23

    $: printf( "Dhis is a pro6ram Eith a " );': doit( "pro-lem!");: return ;8: *

    0. >ake the following change to the program in e2ercise 8. !ecompile and rerunthis program. What does the program do now9

    : printf( "9c", 1 );

    ost of thisbook is devoted to e2plaining these various program components and how you use them.

    To get the overall picture, however, you should begin by seeing a complete though

    small/ C program with all its components identified. Today you will learn

    About a short C program and its components

    The purpose of each program component

  • 8/11/2019 C IN 21 DAYS

    14/23

    How to compile and run a sample program

    A $hort C Program

    #isting '.$ presents the source code for >*#T4#Y.C. This is a very simple program. All

    it does is input two numbers from the keyboard and calculate their product. At this stage,don(t worry about understanding the details of the program(s workings. The point is to

    gain some familiarity with the parts of a C program so that you can better understand thelistings presented later in this book.

    "efore looking at the sample program, you need to know what a function is, because

    functions are central to C programming. Afunctionis an independent section of program

    code that performs a certain task and has been assigned a name. "y referencing afunction(s name, your program can e2ecute the code in the function. The program also

    can send information, called ar$uments,to the function, and the function can return

    information to the main part of the program. The two types of C functions are library

    functions,which are a part of the C compiler package, and user"defined functions,whichyou, the programmer, create. You will learn about both types of functions in this book.

    +ote that, as with all the listings in this book, the line numbers in #isting '.$ are not part

    of the program. They are included only for identification purposes, so don(t type them.

    Listing 2.1. 5ULT8PL.C.

    1: F= Gro6ram to calculate the product of tEo num-ers. =F: #include :: int a,-,c;$:': int product(int 4, int );:8: main(): 1: F= nput the first num-er =F11: printf("+nter a num-er -etEeen 1 and 1: ");1: scanf("9d", a);1:1: F= nput the second num-er =F1$: printf("+nter another num-er -etEeen 1 and 1: ");1': scanf("9d", -);1:

    18: F= Ialculate and displa the product =F1: c product(a, -);: printf ("9d times 9d 9d&n", a, -, c);1:: return ;: *:$: F= 7unction returns the product of its tEo ar6uments =F': int product(int 4, int ):

  • 8/11/2019 C IN 21 DAYS

    15/23

    8: return (4 = );: *+nter a num-er -etEeen 1 and 1: 35+nter another num-er -etEeen 1 and 1:23$ times 8$

    The Programs Components

    The following sections describe the various components of the preceding sampleprogram. #ine numbers are included so that you can easily identify the program parts

    being discussed.

    The main:; -un#tion :Lines Through 23;

    The only component that is re3uired in every C program is the main/ function. n its

    simplest form, the main/ function consists of the name main followed by a pair of empty

    parentheses // and a pair of braces MN/. Within the braces are statements that make upthe main body of the program. *nder normal circumstances, program e2ecution starts at

    the first statement in main/ and terminates at the last statement in main/.

    The in#"u%e ire#ti!e :Line 2;

    The Oinclude directive instructs the C compiler to add the contents of an include file into

    your program during compilation. An include fileis a separate disk file that contains

    information needed by your program or the compiler. 5everal of these files sometimescalled header files/ are supplied with your compiler. You never need to modify the

    information in these filesD that(s why they(re kept separate from your source code. nclude

    files should all have an .H e2tension for e2ample, 5TB.H/.

    You use the Oinclude directive to instruct the compiler to add a specific include file toyour program during compilation. The Oinclude directive in this sample program means

    LAdd the contents of the file 5TB.H.L >ost C programs re3uire one or more include

    files. >ore information about include files is presented on ay '$, LAdvanced Compiler*se.L

    The Daria,"e efinition :Line 4;

    A ariableis a name assigned to a data storage location. Your program uses variables to

    store various kinds of data during program e2ecution. n C, a variable must be definedbefore it can be used. A variable definition informs the compiler of the variable(s name

    and the type of data it is to hold. n the sample program, the definition on line , int

    a,b,cD, defines three variables11named a, b, and c11that will each hold an integer value.>ore information about variables and variable definitions is presented on ay 8, L5toring

    ata) ?ariables and Constants.L

    The -un#tion Prototype :Line 0;

  • 8/11/2019 C IN 21 DAYS

    16/23

    Afunction #rototy#eprovides the C compiler with the name and arguments of the

    functions contained in the program. t must appear before the function is used. A function

    prototype is distinct from afunction definition,which contains the actual statements thatmake up the function. 0unction definitions are discussed in more detail later in this

    chapter./

    Program $tatements :Lines 119 129 1/9 109 19 29 229 an% 2;

    The real work of a C program is done by its statements. C statements display information

    on1screen, read keyboard input, perform mathematical operations, call functions, read

    disk files, and carry out all the other operations that a program needs to perform. >ost ofthis book is devoted to teaching you the various C statements. 0or now, remember that in

    your source code, C statements are generally written one per line and always end with a

    semicolon. The statements in >*#T4#Y.C are e2plained briefly in the followingsections.

    printf:;

    The printf/ statement lines $$, $F, and 'G/ is a library function that displays information

    on1screen. The printf/ statement can display a simple te2t message as in lines $$ and $F/

    or a message and the value of one or more program variables as in line 'G/.

    s#anf:;

    The scanf/ statement lines $' and $/ is another library function. t reads data from the

    keyboard and assigns that data to one or more program variables.

    The program statement on line $% calls the function named product/. n other words, ite2ecutes the program statements contained in the function product/. t also sends thearguments a and b to the function. After the statements in product/ are completed,

    product/ returns a value to the program. This value is stored in the variable named c.

    return

    #ines '' and '7 contain return statements. The return statement on line '7 is part of thefunction product/. t calculates the product of the variables 2 and y and returns the result

    to the program statement that called product/. The return statement on line '' returns a

    value of G to the operating system =ust before the program ends.

    The -un#tion efinition :Lines 20 Through 2;

    A function is an independent, self1contained section of code that is written to perform a

    certain task.

  • 8/11/2019 C IN 21 DAYS

    17/23

    The function named product/, in lines ' through '%, is a user1defined function. As the

    name implies, user1defined functions are written by the programmer during program

    development. This function is simple. All it does is multiply two values and return theanswer to the program that called it. Bn ay F, L0unctions) The "asics,L you will learn

    that the proper use of functions is an important part of good C programming practice.

    +ote that in a real C program, you probably wouldn(t use a function for a task as simple

    as multiplying two numbers. (ve done this here for demonstration purposes only.

    C also includes library functions that are a part of the C compiler package. #ibrary

    functions perform most of the common tasks such as screen, keyboard, and disk

    inputEoutput/ your program needs. n the sample program, printf/ and scanf/ are libraryfunctions.

    Program Comments :Lines 19 19 149 19 an% 2/;

    Any part of your program that starts with EP and ends with PE is called a comment. Thecompiler ignores all comments, so they have absolutely no effect on how a program

    works. You can put anything you want into a comment, and it won(t modify the way your

    program operates. A comment can span part of a line, an entire line, or multiple lines.

    Here are three e2amples)

    F= sin6leJline comment =Fint a,-,c; F= partialJline comment =FF= a commentspannin6multiple lines =F

    However, you shouldn(t use nestedcomments in other words, you shouldn(t put onecomment within another/. >ost compilers would not accept the following)

    F=F= Kested comment =F=F

    5ome compilers do allow nested comments. Although this feature might be tempting to

    use, you should avoid doing so. "ecause one of the benefits of C is portability, using a

    feature such as nested comments might limit the portability of your code. +ested

    comments also might lead to hard1to1find problems.

    >any beginning programmers view program comments as unnecessary and a waste oftime. This is a mistake The operation of your program might be 3uite clear while you(re

    writing it11particularly when you(re writing simple programs. However, as your programsbecome larger and more comple2, or when you need to modify a program you wrote si2

    months ago, you(ll find comments invaluable. +ow is the time to develop the habit of

    using comments liberally to document all your programming structures and operations.

  • 8/11/2019 C IN 21 DAYS

    18/23

    '(T&)>any people have started using a newer style of comments in their C programs.

    Within C@@ and ;ava, you can use double forward slashes to signal a comment. Here are

    two e2amples)FF Dhis entire line is a commentint 4; FF Iomment starts Eith slashes.

    The two forward slashes signal that the rest of the line is a comment. Although many Ccompilers support this form of comment, you should avoid it if you(re interested in

    portability.

    (add abundant comments to your program(s source code, especially near statements or

    functions that could be unclear to you or to someone who might have to modify it later.

    ('Tadd unnecessary comments to statements that are already clear. 0or e2ample,

    entering

    F= Dhe folloEin6 prints Hello %orld! on the screen =Fprintf("Hello %orld!");

    might be going a little too far, at least once you(re completely comfortable with the

    printf/ function and how it works.

    (learn to develop a style that will be helpful. A style that(s too lean or cryptic doesn(thelp, nor does one that(s so verbose that you(re spending more time commenting than

    programming

    Bra#es :Lines 9 239 29 an% 2;

    You use braces MN/ to enclose the program lines that make up every C function11

    including the main/ function. A group of one or more statements enclosed within bracesis called a block. As you will see in later chapters, C has many uses for blocks.

    unning the Program

    Take the time to enter, compile, and run >*#T4#Y.C. t provides additional practice in

    using your editor and compiler. !ecall these steps from ay $, LJetting 5tarted with CL)

    1. >ake your programming directory current.

    2. 5tart your editor.

    3. *#T4#Y.C e2actly as shown in #isting '.$, but besure to omit the line numbers and colons.

    4. 5ave the program file.

  • 8/11/2019 C IN 21 DAYS

    19/23

    /. Compile and link the program by entering the appropriate commands/ for your

    compiler. f no error messages are displayed, you can run the program by entering

    multiply at the command prompt.

    0. f one or more error messages are displayed, return to step ' and correct the

    errors.

    A 'ote on A##ura#y

    A computer is fast and accurate, but it also is completely literal. t doesn(t know enough

    to correct your simplest mistakeD it takes everything you enter e2actly as you entered it,

    not as you meant it

    This goes for your C source code as well. A simple typographical error in your program

    can cause the C compiler to choke, gag, and collapse. 0ortunately, although the compiler

    isn(t smart enough to correct your errors and you(ll make errors11everyone does/, it is

    smart enough to recogni6e them as errors and report them to you. You saw in the

    preceding chapter how the compiler reports error messages and how you interpret them./

    A e!ie of the Parts of a Program

    +ow that all the parts of a program have been described, you should be able to look at

    any program and find some similarities. #ook at #isting '.' and see whether you canidentify the different parts.

    Listing 2.2. L8$TE8T.C.

    1: F= 5LDD.IJJDhis pro6ram displas a listin6 Eith line num-ers! =F

    : #include : #include :$: oid displausa6e(oid);': int line;:8: main( int ar6c, char =ar6NO ): 1: char -ufferN$'O;11: 75+ =fp;1:1: if( ar6c < )1: 1$: displausa6e();1': e4it(1);1: *18:1: if (( fp fopen( ar6N1O, "r" )) KP55 ): 1: fprintf( stderr, "+rror openin6 file, 9s!", ar6N1O );: e4it(1);: *:

  • 8/11/2019 C IN 21 DAYS

    20/23

    $: line 1;':: Ehile( f6ets( -uffer, $', fp ) ! KP55 )8: fprintf( stdout, "9d:&t9s", line??, -uffer );:: fclose(fp);1: return ;: *:: oid displausa6e(oid)$: ': fprintf(stderr, "&nGroper Psa6e is: " );: fprintf(stderr, "&n&n5LDD filename.e4t&n" );8: *I:&>list_it list_it.c1: F= 5LDD.I J Dhis pro6ram displas a listin6 Eith line num-ers! =F: #include : #include :$: oid displausa6e(oid);

    ': int line;:8: main( int ar6c, char =ar6NO ): 1: char -ufferN$'O;11: 75+ =fp;1:1: if( ar6c < )1: 1$: displausa6e();1': e4it(1);1: *18:1: if (( fp fopen( ar6N1O, "r" )) KP55 ): 1: fprintf( stderr, "+rror openin6 file, 9s!", ar6N1O );: e4it(1);: *:$: line 1;':: Ehile( f6ets( -uffer, $', fp ) ! KP55 )8: fprintf( stdout, "9d:&t9s", line??, -uffer );:: fclose(fp);1: return ;: *

    :: oid displausa6e(oid)$: ': fprintf(stderr, "&nGroper Psa6e is: " );: fprintf(stderr, "&n&n5LDD filename.e4t&n" );8: *

  • 8/11/2019 C IN 21 DAYS

    21/23

    A'AL$8$) #5TQT.C is similar to 4!+TQT.C, which you entered in e2ercise & of

    ay $. #isting '.' displays saved C program listings on1screen instead of printing them

    on the printer.

    #ooking at this listing, you can summari6e where the different parts are. The re3uired

    main/ function is in lines 7 through 8'. #ines ' and 8 have Oinclude directives. #ines ,$G, and $$ have variable definitions. A function prototype, void displayQusagevoid/, is in

    line F. This program has many statements lines $8, $F, $, $%, '$, '', 'F, '&, '7, 8G, 8$,8, and 8&/. A function definition for displayQusage/ fills lines 8 through 87. "races

    enclose blocks throughout the program. 0inally, only line $ has a comment. n most

    programs, you should probably include more than one comment line.

    #5TQT.C calls many functions. t calls only one user1defined function, displayQusage/.

    The library functions that it uses are e2it/ in lines $ and ''D fopen/ in line $%D fprintf/

    in lines '$, '7, 8, and 8&D fgets/ in line '&D and fclose/ in line 8G. These library

    functions are covered in more detail throughout this book.

    $ummary

    This chapter was short, but it(s important, because it introduced you to the ma=or

    components of a C program. You learned that the single re3uired part of every C program

    is the main/ function. You also learned that the program(s real work is done by programstatements that instruct the computer to perform your desired actions. This chapter also

    introduced you to variables and variable definitions, and it showed you how to use

    comments in your source code.

    n addition to the main/ function, a C program can use two types of subsidiary functions)

    library functions, supplied as part of the compiler package, and user1defined functions,created by the programmer.

    67A

    6 What effe#t %o #omments ha!e on a program?

    AComments are for the programmer. When the compiler converts the source

    code to ob=ect code, it throws the comments and the white space away. This

    means that they have no effect on the e2ecutable program. Comments do makeyour source file bigger, but this is usually of little concern. To summari6e, you

    should use comments and white space to make your source code as easy tounderstand and main1tain as possible.

    6 What is the %ifferen#e ,eteen a statement an% a ,"o#*?

    AA block is a group of statements enclosed in braces MN/. A block can be used in

    most places that a statement can be used.

    6 Ho #an 8 fin% out hat "i,rary fun#tions are a!ai"a,"e?

    A>any compilers come with a manual dedicated specifically to documenting the

    library functions. They are usually in alphabetical order. Another way to find out

  • 8/11/2019 C IN 21 DAYS

    22/23

    what library functions are available is to buy a book that lists them. Appendi2

    1. What is the term for a group of one or more C statements enclosed in braces9

    2. What is the one component that must be present in every C program9

    3. How do you add program comments, and why are they used9

    4. What is a function9/. C offers two types of functions. What are they, and how are they different9

    0. What is the Oinclude directive used for9

    . Can comments be nested9

    . Can comments be longer than one line9

    . What is another name for an include file9

    1. What is an include file9

    &+er#ises

    1. Write the smallest program possible.

    2. Consider the following program)1: F= [email protected] =F: #include :: oid displaline(oid);$:': main(): 8: displaline();: printf("&n Deach Courself I n 1 Qas!&n");1: displaline();11:1: return ;

    1: *1:1$: F= print asterisB line =F1': oid displaline(oid)1: 18: int counter;1:: for( counter ; counter < 1; counter?? )1: printf("=" );: *

  • 8/11/2019 C IN 21 DAYS

    23/23