THEORY AND PROBLEMS OF PROGRAMMING WITH Second Edition phần 3 doc

55 388 0
THEORY AND PROBLEMS OF PROGRAMMING WITH Second Edition phần 3 doc

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

102 PREPARING AND RUNNING A COMPLETE C PROGRAM [CHAP. 5 4. Determine the future accumulation (F) using the formula F=P(l +i)" 5. Display the calculated value for F. Here is the program outline in the form of pseudocode. /* compound interest calculations */ main ( ) { /* declare the program variables */ /* read in values for P, r and n */ /* calculate a value for i */ /* calculate a value for F */ /* display the calculated value for F */ 1 Each of these steps appears very simple when viewed from the top. However, some steps require more detail before they can actually be programmed. For example, the data input step will be carried out interactively. This will require some dialog generated by pairs of printf and scanf statements, as explained in the Chap. 4. Moreover, C does not have an exponentiation operator. Therefore, some additional detail will be required in order to evaluate the formula F=P(l +i)" Here is a more detailed version of the above outline. /* compound interest calculations */ main ( ) { /* declare p, r, n, i and f to be floating-point variables */ /* write a prompt for p and then read in its value */ /* write a prompt for r and then read in its value */ /* write a prompt for n and then read in its value */ /* calculate i = r/100 */ /* calculate f = p (1 + i)" as follows: f = p * pow((l+i),n) where POW is a library function for exponentiation */ /* display the value for f, with an accompanying label */ This outline involves more detail than is actually necessary for a program this simple, though it does illustrate the top- down approach to program development. We will consider the detailed development and implementation of this program later in this chapter, in Examples 5.2, 5.4 and 5.5. Another method that is sometimes used when planning a C program is the "bottom-up" approach. This method may be useful for programs that make use of self-contained program modules (e.g., user-defined functions). The bottom-up approach involves the detailed development of these program modules early in the planning process. The overall program development is then based upon the known characteristics of these available program modules. 103 CHAP. 51 PREPARING AND RUNNING A COMPLETE C PROGRAM In practice we often use both approaches: top-down for the overall program planning, bottom-up in developing individual modules before the main part of the program, and top-down with respect to the development of each individual module. 5.2 WRITING A C PROGRAM Once an overall program strategy has been formulated and a program outline has been written, attention can be given to the detailed development of a working C program. At this point the emphasis becomes one of translating each step of the program outline (or each portion of the pseudocode) into one or more equivalent C instructions. This should be a straightforward activity provided the overall program strategy has been thought through carefully and in enough detail. You should understand, however, that there is more to writing a complete C program than simply arranging the individual declarations and statements in the right order and then punctuating them correctly. Attention should also be given to including certain additional features that will improve the readability of the program and its resulting output. These features include the logical sequencing of the statements, the use of indentation and whitespace, the inclusion of comments and the generation of clearly labeled output. The selection of the program statements and their logical sequencing within the program is, to a large extent, determined by the underlying program logic. Often, however, there will be several different choices available for obtaining the same end result. This is particularly true of more complex programs that involve the use of conditional or repeated program segments. In such cases, the manner in which the program is organized can have a major effect on the logical clarity of the program and the efficiency of execution. Therefore it is important that the statements be selected and sequenced in the most effective manner. We will say more about this in Chap. 6, where we discuss the various types of conditional and repetitive features that are available in C. The use of indentation is closely related to the sequencing of groups of statements within a program. Whereas sequencing affects the order in which a group of operations is carried out, indentation illustrates the subordinate nature of individual statements within a group. In addition, blank lines are sometimes used to separate related groups of statements. The value of the indentation and the blank lines should be obvious, even in the simple programs presented earlier in this book. This will become even more apparent later, as we encounter C programs whose structure is more complex. Comments should always be included within a C program. If written properly, comments can provide a useful overview of the general program logic. They can also delineate major segments of a program, identify certain key items within the program and provide other useful information about the program. Generally, the comments need not be extensive; a few well-placed comments can shed a great deal of light on an otherwise obscure program. Such comments can be of great use to the original programmer as well as to other persons trying to read and understand a program, since most programmers do not remember the details of their own programs over a period of time. This is especially true of programs that are long and complicated. Another important characteristic of a well-written program is its ability to generate clear, legible output. Two factors contribute to this legibility. The first is labeling of the output data, as we have discussed in Chap. 4. The second is the appearance of some of the input data along with the output, so that each instance of program execution (if there are more than one) can be clearly identified. The manner in which this is accomplished depends upon the environment in which the C program will be executed. In an interactive environment the input data is displayed on the screen at the time of data entry, during program execution. Hence the input data need not be displayed again. When executing an interactive program, the user (someone other than the programmer) may not know how to enter the required input data. For example, the user may not know what data items are required, when the data items should be entered, or the order in which they should be entered. Thus a well-written interactive program should generate prompts at appropriate times during the program execution in order to provide this information. EXAMPLE 5.2 Compound Interest Let us now consider an interactive C program corresponding to the outline presented in Example 5.1. 104 PREPARING AND RUNN?NG A COMPLETE C PROGRAM [CHAP. 5 /* simple compound interest problem */ #include <stdio.h> #include <math.h> main ( ) float p, r, n, i, f; /* read input data (including prompts) */ printf("P1ease enter a value for the principal (P): "); scanf ( "%fn , &p) ; printf("P1ease enter a value for the interest rate (r): I"); scanf ("%f" , &r) ; printf("P1ease enter a value for the number of years (n): "); scanf ("%f", an) ; /* calculate i, then f */ i = r/100; f = p * pow((1 + i),n); /* display the output */ printf("\nThe final value (F) is: %.2f\nNJ f); The program shown in this example is logically very straightforward. Thus we did not have to concern ourselves with alternate ways to sequence the statements. There are, however, some other desirable features that might have been included. For example, we might want to execute the program repetitively, for several different sets of input data. Or, we might want to add error traps that prevent the user from entering negative values for any of the input parameters. In Chap. 6 we will see how these features can be added. 5.3 ENTERING THE PROGRAM INTO THE COMPUTER Once the program has been written, it must be entered into the computer before it can be compiled and executed. In older versions of C this was done by typing the program into a text file on a line-by-line basis, using a text editor or a word processor. Most contemporary versions of C or C++ include a screen editor that is used for this purpose. The editor is usually integrated into the software environment. Thus, to access the editor, you must first enter the C or C++ programming environment. The manner in which this accomplished varies from one implementation of C to another. Consider, for example, Version 4.5 Turbo C++, running under Windows on an IBM-compatible personal computer. To enter Turbo C++, open the Turbo C++ group and then click on the Turbo C++ icon. This will result in the near-empty window shown in Fig. 5.1. Within this window, the first line (containing Turbo C++ - [ nonameOO. cpp]), is the titZe bar, and the second line (containing File Edit Search View, etc.) is the menu bar. Selecting one of the items in the menu bar will cause a drop-down menu to appear, with a number of choices related to the menu bar selection. For example, the File menu includes choices that allow you to open a new program, retrieve an existing program, save a program, print a program listing, or exit from Turbo C++. We will discuss some of these drop-down menu selections later in this chapter. Usually a pointing device, such as a mouse, is used to select a menu item. This is accomplished by moving the cursor over the desired item and then "clicking" on the item; i.e., pressing a button on the pointing device. The large clear space beneath the menu bar is an editing area where a new program can be entered or an existing program displayed. Portions of the program listed in this area can be changed, deleted, copied or 105 CHAP. 51 PREPARING AND RUNNING A COMPLETE C PROGRAM moved to another part of the program. Some of these changes are made directly in the editing area, while others are made by highlighting (i.e., selecting) a part of the program and then copying, moving or deleting the highlighted material using the selections provided in the Edit menu. Highlighting is usually carried out by holding down a mouse button and then dragging the mouse across the material to be highlighted. Scroll bars are present beneath and to the right of the editing area, The scroll bars allow you to move quickly to other parts of the program if the program listing extends beyond the confines of the screen. Thus, you can move vertically through the program listing by clicking along the right scroll bar, or by dragging the small square scroll button up or down. Similarly, you can move horizontally across the program listing by clicking along the bottom scroll bar, or by dragging the scroll button to the right or the left. Finally, the last line is the status bar, which indicates the current status of the editing area, or the purpose of the currently highlighted menu selection. Figure 5.1 indicates that the editing window is in the insert mode, meaning that text can be inserted anywhere within the window. Fig. 5.1 To enter a new program in Turbo C++, you simply type the program into the editing area on a line-by-line basis and press the Enter key at the end of each line. To edit a line, use the mouse or the cursor movement (arrow) keys to locate the beginning of the edit area. Then use the Backspace or Delete keys to remove unwanted characters. You may also insert additional characters, as required. You may delete one or more lines simply by highlighting the lines and then selecting Cut from the Edit menu, or by pressing the Delete key. A block of lines can be moved to another location using the Cut and Paste selections in the Edit menu. Similarly, a block of lines can be copied to another location using the Copy and Paste selections in the Edit menu. Additional editing instructions are provided in the Turbo C++ User’s Manual. Once the program has been entered, it should be saved before it is executed. In Turbo C++, this is accomplished by selecting Save As from the File menu, and then supplying a program name, such as INTEREST. C. (The extension C will be added automatically if an extension is not included as a part of the file 106 PREPARING AND RUNNING A COMPLETE C PROGRAM [CHAP. 5 name.) Once the program has been saved and a name has been provided, it can again be saved at some later time (with, for example, any recent editing changes), simply by selecting Save from the File menu. A program that has been saved can later be recalled by selecting Open from the File menu, and then either typing the program name or selecting the program name from a list of stored programs. A printed listing of the current program (called a “hard copy”) can be obtained at any time by selecting Print from the File menu. EXAMPLE 5.3 Compound Interest Suppose you have entered the compound interest program shown in Example 5.2 into an IBM-compatible personal computer using Turbo C++. After all typing corrections have been made, the screen will appear as shown in Fig. 5.2. You can then save the program by selecting Save As from the File menu, as shown in Fig. 5.3. Once you select Save As, a dialog box will appear, requesting the name of the program being saved. Respond by entering the program name INTEREST. C. You may then conclude the session by selecting Exit from the File menu. Fig. 5.2 5.4 COMPILING AND EXECUTING THE PROGRAM Once the program has been entered into the computer, edited and saved, it can be compiled and executed by selecting Run from the Debug menu. A new window will then be opened, and an attempt will be made to compile the current program. If the program does not compile successfully, a list of error messages will appear in a separate window. Each error message indicates the line number where the error was detected as well as the type of error. If the program does compile successfully, however, it will immediately begin to execute, prompting for input, displaying output, etc., within the new window. EXAMPLE 5.4 Compound Interest Suppose you reenter Turbo C++ after concluding the session described in Example 5.3. Start by loading the previous program, INTEREST. C, into the computer’s memory, by selecting Open from the File menu. Then select Run from the Debug menu, as shown in Fig. 5.4. 107 CHAP. 51 PREPARING AND RUNNING A COMPLETE C PROGRAM 108 PREPARING AND RUNNING A COMPLETE C PROGRAM [CHAP. 5 CHAP. 51 PREPARING AND RUNNING A COMPLETE C PROGRAM 109 The program is compiled successfully and immediately begins to execute. A new window, showing the inputloutput dialog, appears on top of the original window containing the program listing. This is shown in Fig. 5.5 for the values P = 1000, r = 6 and n = 20. These values have been entered by the user, in response to the input prompts. Once the last input quantity has been entered (n = 20), the program resumes execution, resulting in the final output shown in Fig. 5.6. Thus, we see that a value of F = 3207.14 is obtained for the given input quantities. 5.5 ERROR DIAGNOSTICS Programming errors often remain undetected until an attempt is made to compile or execute the program. The presence of syntactic (or grammatical) errors will become readily apparent once the Run command has been issued, since these errors will prevent the program from being compiled or executed successfully. Some particularly common errors of this type are improperly declared variables, a reference to an undeclared variable, incorrect punctuation, etc. Most C compilers will generate diagnostic messages when syntactic errors have been detected during the compilation process. These diagnostic messages are not always straightforward in their meaning and they may not correctly identify where the error occurred (though they may attempt to do so). Nevertheless, they are helpful in identifying the nature and the approximate location of the errors. If a program includes several different syntactic errors, they may not all be detected on the first pass through the compiler. Thus, it may be necessary to correct some syntactic errors before others can be found. This process could repeat itself through several cycles before all of the syntactic errors have been identified and corrected. EXAMPLE 5.5 Syntactic Errors Here is another version of the compound interest program shown in Examples 5.2 through 5.4. /* simple compound interest problem */ #include <stdio.h> include <math.h> main ( ) .i float p, r, n, i, f; /* read input data (including prompts) */ printf("P1ease enter a value for the principal (P): "); scanf ("%f &p) ; 'I, printf("P1ease enter a value for the interest rate (r): ); scanf ( "%f &r) ; 'I, printf("P1ease enter a value for the number of years (n): "); scanf ( "%f an) 'I, /* calculate i, then f */ i = r/100; f = p * pow(1 + i),n); /* write output /* printf("\nThe final value (F) is: %.2f\n", f); This version of the program contains five different syntactic errors. The errors are as follows: 1. The second include statement does not begin with a # sign. 2. The control string in the second printf statement does not have a closing quotation mark. 110 PREPARING AND RUNNING A COMPLETE C PROGRAM [CHAP. 5 3. The last scanf statement does not end with a semicolon. 4. The assignment statement for f contains unbalanced parentheses. 5. The last comment closes improperly (it ends with / * instead of * /). When a compilation was attempted (by selecting either Run from the Debug menu or Compile from the Project menu), the error messages shown in Fig. 5.7 were obtained within a separate message window. The first message refers to the missing # sign in line 4 (the line numbers include empty lines). The second message refers to the missing double quote (") at the end of the second printf statement (line 15), and the third message refers to the improper ending of the last comment (line 25). Notice that the error messages are somewhat cryptic. Thus, some ingenuity may be required to determine what they mean. When these three errors were correctly identified and corrected, another attempt was made to compile the program. This resulted in the new set of error messages shown in Fig. 5.8. The first error message refers to the missing semicolon at the end of the last scanf statement (which actually occurs in line 18, not line 22). The second message refers to the missing left parenthesis in second assignment statement (line 23). The following two warnings and the third error message are also a result of this one error. When these remaining two errors were corrected, the program compiled correctly and began to execute, as shown in Fig. 5.5. You should understand that the specific error messages and warnings will vary from one version of C to another. Some compilers may generate messages that are longer or more informative than those shown in this example, though the messages shown here are typical. Another type of error that is quite common is the execution error. Execution errors occur during program execution, after a successful compilation. For example, some common execution errors are a numerical overflow of underflow (exceeding the largest or smallest permissible number that can be stored in the computer), division by zero, attempting to compute the logarithm or the square root of a negative number, etc. Diagnostic messages will often be generated in situations of this type, making it easy to identify and correct the errors. These diagnostics are sometimes called execution messages or run-time messages, to distinguish them from the compilation messages described earlier. CHAP. 51 PREPARING AND RUNNING A COMPLETE C PROGRAM 111 EXAMPLE 5.6 Real Roots of a Quadratic Equation Suppose we want to calculate the real roots of the quadratic equation using the quadratic formula -bfJb2-4ac X= 242 Here is a C program that will carry out these calculations. /* real roots of a quadratic equation */ #include <stdio.h> #include Cmath. h> main ( ) float a, b, c, d, xl, x2; /* read input data */ printf ("a = 'I); scanf ( "%f ", &a) ; printf('b = "); scanf ( "%f &b) ; 'I, printf ("c = ") ; scanf ('%f ', &c) ; /* carry out the calculations */ d = sqrt(b * b - 4 * a * c); xl = (-b + d) / (2 * a); x2 = (-b - d) / (2 * a); /* display the output */ printf ('\nxl = %e x2 = %e", xl, x2); 1 This program is completely free of syntactic errors, but it is unable to accommodate negative values for b2 - 4ac. Furthermore, numerical difficulties may be encountered if the variable U has a very small or a very large numerical value, or if a = 0. A separate error message will be generated for each of these errors. Suppose, for example, the program is run with Turbo C++ using the following input values: a=l .O b=2.0 c=3.0 The program compiles without any difficulty. When the object program is executed, however, the following error message is generated, after the input values have been entered into the computer. sqrt: DOMAIN error Everything then comes to a halt, since the program execution cannot continue beyond this point. Figure 5.9 illustrates the appearance of the screen in Turbo C++. [...]... statements and replace them with three other p r i n t f statements (i.e., three tracing statements) The first p r i n t f statement will display the values of a, b, c and d, the second will display the value of (-b + d), and the last will display the value of (-b - d), as shown below (Notice the placement of the three p r i n t f statements, together after the calculation of d but before the calculation of. .. statements, one within another There are several different forms that nested if - e l s e statements can take The most general form of two-layer nesting is if e7 if e2 s7 e l s e s2 e l s e if e3 s3 e l s e s4 where e I, e2 and e3 represent logical expressions and s 7, s2, s3 and s4 represent statements Now, one complete if - e l s e statement will be executed if e7 is nonzero (true), and another complete... require the repeated execution of groups of statements, and they did not involve the execution of individual groups of statements on a selective basis Most C programs that are of practical interest make extensive use of features such as these For example, a realistic C program may require that a logical test be carried out at some particular point within the program One of several possible actions will... t is assigned a value of 0 The w h i l e loop then displays the current value of d i g i t , increases its value by 1 and then repeats the cycle, until the value of d i g i t exceeds 9 The net effect is that the body of the loop will be repeated 10 times, resulting in 10 consecutive lines of output Each line will contain a successive integer value, beginning with 0 and ending with 9 Thus, when the... one of the numbers in the list Each number will be represented by the floating-point variable x (b) Add the value of x to the current value of sum (c) Increase the value of count by 1 5 Divide the value of sum by n to obtain the desired average 6 Write out the calculated value for the average Here is the complete C program Notice that steps 3 and 4 are combined in the f o r statement, and that steps 3. .. 5.1 What is meant by “top-down’’ programming? What are its advantages? How is it carried out? 5.2 What is pseudocode? What advantage is there in using pseudocode to plan a new program? 5 .3 What is meant by “bottom-up” programming? How does it differ from top-down programming? 5.4 How much flexibility does the programmer have in the logical sequencing of the statements within a C program? Explain 5.5... review some concepts presented in Chaps 2 and 3 that must be used in conjunction with these statements Understanding these concepts is essential in order to proceed fiuther First, we will need to form logical expressions that are either true or false To do so, we can use the four relational operators, =, and the two equality operators, == and ! = (see Sec 3. 3) EXAMPLE 6.1 Several logical expressions... CHAP.61 CONTROL STATEMENTS 1 23 In addition to the relational and equality operators, C contains two logical connectives (also called logical operators), && (AND) and I I (OR), and the unary negation operator ! (see Sec 3. 3) The logical connectives are used to combine logical expressions, thus forming more complex expressions The negation operator is used to reverse the meaning of a logical expression (e.g.,... The second example examines the past-due status of an account If the value of pastdue exceeds zero, a message is displayed and the credit limit is set at zero; otherwise, the credit limit is set at 1000.0 In the third example, the value of y is computed differently, depending on whether or not the corresponding value of x exceeds 3 The fourth example shows how an area can be calculated for either of. .. assigned a nonzero value, the radius of a circle is read into the computer, the area is calculated and then displayed If the value of circle is zero, however, then the length and width of a rectangle are read into the computer, the area is calculated and then displayed In each case, the type of geometric figure is included in the label that accompanies the value of the area It is possible to nest (i.e., . sequencing of the statements, the use of indentation and whitespace, the inclusion of comments and the generation of clearly labeled output. The selection of the program statements and their. discuss the various types of conditional and repetitive features that are available in C. The use of indentation is closely related to the sequencing of groups of statements within a program. Whereas. first is labeling of the output data, as we have discussed in Chap. 4. The second is the appearance of some of the input data along with the output, so that each instance of program execution

Ngày đăng: 13/08/2014, 18:20

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan