c1-1 (779455), страница 2
Текст из файла (страница 2)
Further reproduction, or any copying of machinereadable files (including this one) to any servercomputer, is strictly prohibited. To order Numerical Recipes books,diskettes, or CDROMsvisit website http://www.nr.com or call 1-800-872-7423 (North America only),or send email to trade@cup.cam.ac.uk (outside North America).An executing program unfolds in time, but not strictly in the linear order inwhich the statements are written. Program statements that affect the order in whichstatements are executed, or that affect whether statements are executed, are calledcontrol statements.
Control statements never make useful sense by themselves. Theymake sense only in the context of the groups or blocks of statements that they in turncontrol. If you think of those blocks as paragraphs containing sentences, then thecontrol statements are perhaps best thought of as the indentation of the paragraphand the punctuation between the sentences, not the words within the sentences.We can now say what the goal of structured programming is.
It is to makeprogram control manifestly apparent in the visual presentation of the program. Yousee that this goal has nothing at all to do with how the computer sees the program.As already remarked, computers don’t care whether you use structured programmingor not. Human readers, however, do care. You yourself will also care, once youdiscover how much easier it is to perfect and debug a well-structured program thanone whose control structure is obscure.You accomplish the goals of structured programming in two complementaryways.
First, you acquaint yourself with the small number of essential controlstructures that occur over and over again in programming, and that are thereforegiven convenient representations in most programming languages. You should learnto think about your programming tasks, insofar as possible, exclusively in terms ofthese standard control structures. In writing programs, you should get into the habitof representing these standard control structures in consistent, conventional ways.“Doesn’t this inhibit creativity?” our students sometimes ask. Yes, justas Mozart’s creativity was inhibited by the sonata form, or Shakespeare’s by themetrical requirements of the sonnet.
The point is that creativity, when it is meant tocommunicate, does well under the inhibitions of appropriate restrictions on format.Second, you avoid, insofar as possible, control statements whose controlledblocks or objects are difficult to discern at a glance. This means, in practice, that youmust try to avoid named labels on statements and goto’s. It is not the goto’s thatare dangerous (although they do interrupt one’s reading of a program); the namedstatement labels are the hazard. In fact, whenever you encounter a named statementlabel while reading a program, you will soon become conditioned to get a sinkingfeeling in the pit of your stomach.
Why? Because the following questions will, byhabit, immediately spring to mind: Where did control come from in a branch to thislabel? It could be anywhere in the routine! What circumstances resulted in a branchto this label? They could be anything! Certainty becomes uncertainty, understandingdissolves into a morass of possibilities.Some examples are now in order to make these considerations more concrete(see Figure 1.1.1).incrementindexblockblockbreakconditiontruefalseblockFigure 1.1.1.
Standard control structures used in structured programming: (a) for iteration; (b) whileiteration; (c) do while iteration; (d) break iteration; (e) if structure; (f) switch structureSample page from NUMERICAL RECIPES IN C: THE ART OF SCIENTIFIC COMPUTING (ISBN 0-521-43108-5)Copyright (C) 1988-1992 by Cambridge University Press.Programs Copyright (C) 1988-1992 by Numerical Recipes Software.Permission is granted for internet users to make one paper copy for their own personal use.
Further reproduction, or any copying of machinereadable files (including this one) to any servercomputer, is strictly prohibited. To order Numerical Recipes books,diskettes, or CDROMsvisit website http://www.nr.com or call 1-800-872-7423 (North America only),or send email to trade@cup.cam.ac.uk (outside North America).BREAK iteration(d)DO WHILE iteration(c)falsewhileconditiontrueWHILE iteration(b)FOR iteration(a)blockblocktruenofalsewhileconditionyesiterationcomplete?91.1 Program Organization and Control Structures...IF structure(e)switchexpressionblocknobreak?yesnoblocknobreak?yesnodefault blockSWITCH structure(f )Figure 1.1.1.
Standard control structures used in structured programming (see caption on previous page).Sample page from NUMERICAL RECIPES IN C: THE ART OF SCIENTIFIC COMPUTING (ISBN 0-521-43108-5)Copyright (C) 1988-1992 by Cambridge University Press.Programs Copyright (C) 1988-1992 by Numerical Recipes Software.Permission is granted for internet users to make one paper copy for their own personal use. Further reproduction, or any copying of machinereadable files (including this one) to any servercomputer, is strictly prohibited. To order Numerical Recipes books,diskettes, or CDROMsvisit website http://www.nr.com or call 1-800-872-7423 (North America only),or send email to trade@cup.cam.ac.uk (outside North America).yescasematch?yescasematch?else blockblockblockblocktruetruetruefalseelse ifcondition...falseelse ifconditionfalseifconditionPreliminariesChapter 1.101.1 Program Organization and Control Structures11Notice how we always indent the block of code that is acted upon by the controlstructure, leaving the structure itself unindented.
Notice also our habit of putting theinitial curly brace on the same line as the for statement, instead of on the next line.This saves a full line of white space, and our publisher loves us for it.if (...) {...}else if (...) {...}else {...}Since compound-statement curly braces are required only when there is morethan one statement in a block, however, C’s if construction can be somewhat lessexplicit than the corresponding structure in FORTRAN or Pascal.
Some care must beexercised in constructing nested if clauses. For example, consider the following:if (b > 3)if (a > 3) b += 1;else b -= 1;/* questionable! */As judged by the indentation used on successive lines, the intent of the writer ofthis code is the following: ‘If b is greater than 3 and a is greater than 3, thenincrement b. If b is not greater than 3, then decrement b.’ According to the rulesof C, however, the actual meaning is ‘If b is greater than 3, then evaluate a. If a isgreater than 3, then increment b, and if a is less than or equal to 3, decrement b.’ Thepoint is that an else clause is associated with the most recent open if statement,no matter how you lay it out on the page. Such confusions in meaning are easilyresolved by the inclusion of braces. They may in some instances be technicallysuperfluous; nevertheless, they clarify your intent and improve the program.
Theabove fragment should be written asif (b > 3) {if (a > 3) b += 1;} else {b -= 1;}Here is a working program that consists dominantly of if control statements:#include <math.h>#define IGREG (15+31L*(10+12L*1582))Gregorian Calendar adopted Oct. 15, 1582.long julday(int mm, int id, int iyyy)In this routine julday returns the Julian Day Number that begins at noon of the calendar datespecified by month mm, day id, and year iyyy, all integer variables. Positive year signifies A.D.;negative, B.C. Remember that the year after 1 B.C. was 1 A.D.{void nrerror(char error_text[]);Sample page from NUMERICAL RECIPES IN C: THE ART OF SCIENTIFIC COMPUTING (ISBN 0-521-43108-5)Copyright (C) 1988-1992 by Cambridge University Press.Programs Copyright (C) 1988-1992 by Numerical Recipes Software.Permission is granted for internet users to make one paper copy for their own personal use.
Further reproduction, or any copying of machinereadable files (including this one) to any servercomputer, is strictly prohibited. To order Numerical Recipes books,diskettes, or CDROMsvisit website http://www.nr.com or call 1-800-872-7423 (North America only),or send email to trade@cup.cam.ac.uk (outside North America).IF structure. This structure in C is similar to that found in Pascal, Algol,FORTRAN and other languages, and typically looks like12Chapter 1.Preliminarieslong jul;int ja,jy=iyyy,jm;}(Astronomers number each 24-hour period, starting and ending at noon, witha unique integer, the Julian Day Number [7].
Julian Day Zero was a very longtime ago; a convenient reference point is that Julian Day 2440000 began at noonof May 23, 1968. If you know the Julian Day Number that begins at noon of agiven calendar date, then the day of the week of that date is obtained by adding1 and taking the result modulo base 7; a zero answer corresponds to Sunday, 1 toMonday, . . . , 6 to Saturday.)While iteration. Most languages (though not FORTRAN, incidentally) providefor structures like the following C example:while (n < 1000) {n *= 2;j += 1;}It is the particular feature of this structure that the control-clause (in this casen < 1000) is evaluated before each iteration.
If the clause is not true, the enclosedstatements will not be executed. In particular, if this code is encountered at a timewhen n is greater than or equal to 1000, the statements will not even be executed once.Do-While iteration. Companion to the while iteration is a related controlstructure that tests its control-clause at the end of each iteration. In C, it lookslike this:do {n *= 2;j += 1;} while (n < 1000);In this case, the enclosed statements will be executed at least once, independentof the initial value of n.Break. In this case, you have a loop that is repeated indefinitely until somecondition tested somewhere in the middle of the loop (and possibly tested in moreSample page from NUMERICAL RECIPES IN C: THE ART OF SCIENTIFIC COMPUTING (ISBN 0-521-43108-5)Copyright (C) 1988-1992 by Cambridge University Press.Programs Copyright (C) 1988-1992 by Numerical Recipes Software.Permission is granted for internet users to make one paper copy for their own personal use.
Further reproduction, or any copying of machinereadable files (including this one) to any servercomputer, is strictly prohibited. To order Numerical Recipes books,diskettes, or CDROMsvisit website http://www.nr.com or call 1-800-872-7423 (North America only),or send email to trade@cup.cam.ac.uk (outside North America).if (jy == 0) nrerror("julday: there is no year zero.");if (jy < 0) ++jy;if (mm > 2) {Here is an example of a block IF-structure.jm=mm+1;} else {--jy;jm=mm+13;}jul = (long) (floor(365.25*jy)+floor(30.6001*jm)+id+1720995);if (id+31L*(mm+12L*iyyy) >= IGREG) {Test whether to change to Gregorian Calja=(int)(0.01*jy);endar.jul += 2-ja+(int) (0.25*ja);}return jul;1.1 Program Organization and Control Structures13for(;;) {[statements before the test]if (...) break;[statements after the test]}[next sequential instruction]Here is a program that uses several different iteration structures.