1、C程序设计语言英文版已改格式汇总CHAPTER 1 - A TUTORIAL INTRODUCTIONLet us begin with a quick introduction in C. Our aim is to show the essential elements of the language in real programs, but without getting bogged down in details, rules, and exceptions.At this point, we are not trying to be complete or even precis
2、e (save that the examples aremeant to be correct). We want to get you as quickly as possible to the point where you canwrite useful programs, and to do that we have to concentrate on the basics: variables andconstants, arithmetic, control flow, functions, and the rudiments of input and output. We ar
3、eintentionally leaving out of this chapter features of C that are important for writing biggerprograms. These include pointers, structures, most of Cs rich set of operators, several control-flow statements, and the standard library.This approach and its drawbacks. Most notable is that the complete s
4、tory on any particularfeature is not found here, and the tutorial, by being brief, may also be misleading. Andbecause the examples do not use the full power of C, they are not as concise and elegant asthey might be. We have tried to minimize these effects, but be warned. Another drawback isthat late
5、r chapters will necessarily repeat some of this chapter. We hope that the repetitionwill help you more than it annoys.In any case, experienced programmers should be able to extrapolate from the material in thischapter to their own programming needs. Beginners should supplement it by writing small,si
6、milar programs of their own. Both groups can use it as a framework on which to hang themore detailed descriptions that begin in Chapter 2.1.1GETTING STARTEDThe only way to learn a new programming language is by writing programs in it. The firstprogram to write is the same for all languages:Print the
7、 wordshello, worldThis is a big hurdle; to leap over it you have to be able to create the program text somewhere,compile it successfully, load it, run it, and find out where your output went. With thesemechanical details mastered, everything else is comparatively easy.In C, the program to print hell
8、o, world is#include main()printf(hello, worldn);Just how to run this program depends on the system you are using. As a specific example, onthe UNIX operating system you must create the program in a file whose name ends in .c , such as hello.c , then compile it with the commandcc hello.c If you haven
9、t botched anything, such as omitting a character or misspelling something, thecompilation will proceed silently, and make an executable file called a.out . If you run a.outby typing the commanda.outit will printhello, worldOn other systems, the rules will be different; check with a local expert.Now,
10、 for some explanations about the program itself. A C program, whatever its size, consistsof functions and variables. A function contains statements that specify the computingoperations to be done, and variables store values used during the computation. C functions arelike the subroutines and functio
11、ns in Fortran or the procedures and functions of Pascal. Ourexample is a function named main . Normally you are at liberty to give functions whatevernames you like, but main is special - your program begins executing at the beginning ofmain. This means that every program must have a main somewhere.m
12、ain will usually call other functions to help perform its job, some that you wrote, and othersfrom libraries that are provided for you. The first line of the program,#include tells the compiler to include information about the standard input/output library; the lineappears at the beginning of many C
13、 source files. The standard library is described in Chapter7 and Appendix B.One method of communicating data between functions is for the calling function to provide alist of values, called arguments, to the function it calls. The parentheses after the functionname surround the argument list. In thi
14、s example, main is defined to be a function that expectsno arguments, which is indicated by the empty list ( ) .The statements of a function are enclosed in braces . The function main contains only onestatement,printf(hello, worldn);A function is called by naming it, followed by a parenthesized list
15、 of arguments, so this callsthe function printf with the argument hello, worldn . printf is a library function thatprints output, in this case the string of characters between the quotes.A sequence of characters in double quotes, like hello, worldn , is called a characterstring or string constant. F
16、or the moment our only use of character strings will be asarguments for printf and other functions.The sequence n in the string is C notation for the newline character, which when printedadvances the output to the left margin on the next line. If you leave out the n (a worthwhileexperiment), you wil
17、l find that there is no line advance after the output is printed. You mustuse n to include a newline character in the printf argument; if you try something likeprintf(hello, world);the C compiler will produce an error message.printf never supplies a newline character automatically, so several calls
18、may be used tobuild up an output line in stages. Our first program could just as well have been written#include main()printf(hello, );printf(world);printf(n);to produce identical output.Notice that n represents only a single character. An escape sequence like n provides ageneral and extensible mecha
19、nism for representing hard-to-type or invisible characters.Among the others that C provides are t for tab, b for backspace, for the double quoteand for the backslash itself. There is a complete list in Section 2.3.Exercise 1-1. Run the hello, world program on your system. Experiment with leavingout
20、parts of the program, to see what error messages you get.Exercise 1-2.Experiment to find out what happens when prints s argument string containsc, where c is some character not listed above.1.2VARIABLES AND ARITHMETIC EXPRESSIONSThe next program uses the formula o C=(5/9)( o F-32) to print the follo
21、wing table of Fahrenheittemperatures and their centigrade or Celsius equivalents:1 -1720 -640 460 1580 26100 37120 48140 60160 71180 82200 93220 104240 115260 126280 137300 148The program itself still consists of the definition of a single function named main . It is longerthan the one that printed
22、hello, world , but not complicated. It introduces several newideas, including comments, declarations, variables, arithmetic expressions, loops , andformatted output.#include /* print Fahrenheit-Celsius table for fahr = 0, 20, ., 300 */main()int fahr, celsius;int lower, upper, step;lower = 0; /* lowe
23、r limit of temperature scale */upper = 300; /* upper limit */step = 20; /* step size */fahr = lower;while (fahr = upper) celsius = 5 * (fahr-32) / 9;printf(%dt%dn, fahr, celsius);fahr = fahr + step;The two lines/* print Fahrenheit-Celsius tablefor fahr = 0, 20, ., 300 */are a comment, which in this
24、case explains briefly what the program does. Any charactersbetween /* and */ are ignored by the compiler; they may be used freely to make a programeasier to understand. Comments may appear anywhere where a blank, tab or newline can.In C, all variables must be declared before they are used, usually a
25、t the beginning of thefunction before any executable statements. A declaration announces the properties ofvariables; it consists of a name and a list of variables, such asint fahr, celsius;int lower, upper, step;The type int means that the variables listed are integers; by contrast with float , whic
26、hmeans floating point, i.e., numbers that may have a fractional part. The range of both int andfloat depends on the machine you are using; 16-bits int s, which lie between -32768 and +32767, are common, as are 32-bit int s. A float number is typically a 32-bit quantity, withat least six significant
27、digits and magnitude generally between about 10 -38 and 10 38 .C provides several other data types besides int and float , including:char character - a single byteshort short integerlong long integerdouble double-precision floating pointThe size of these objects is also machine-dependent. There are
28、also arrays, structures andunions of these basic types, pointers to them, and functions that return them, all of which wewill meet in due course.Computation in the temperature conversion program begins with the assignment statementslower = 0;upper = 300;step = 20;which set the variables to their ini
29、tial values. Individual statements are terminated bysemicolons.Each line of the table is computed the same way, so we use a loop that repeats once per outputline; this is the purpose of the while loopwhile (fahr = upper) .The while loop operates as follows: The condition in parentheses is tested. If
30、 it is true ( fahris less than or equal to upper ), the body of the loop (the three statements enclosed in braces)is executed. Then the condition is re-tested, and if true, the body is executed again. When thetest becomes false ( fahr exceeds upper ) the loop ends, and execution continues at thestat
31、ement that follows the loop. There are no further statements in this program, so itterminates.The body of a while can be one or more statements enclosed in braces, as in the temperatureconverter, or a single statement without braces, as inwhile (i j)i = 2 * i;In either case, we will always indent th
32、e statements controlled by the while by one tab stop(which we have shown as four spaces) so you can see at a glance which statements are insidethe loop. The indentation emphasizes the logical structure of the program. Although Compilers do not care about how a program looks, proper indentation and spacing are criticalin making programs easy f
copyright@ 2008-2022 冰豆网网站版权所有
经营许可证编号:鄂ICP备2022015515号-1