c for engineers and scientists introduction to programming with ansi c phần 5 pptx

67 990 0
c for engineers and scientists introduction to programming with ansi c phần 5 pptx

Đ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

6.2 Array Initialization If the number of initializers is less than the declared number of elements list- ed in square brackets, the initializers are applied starting with array element zero. Thus, in the declaration float length[7] = {7.8, 6.4, 4.9, 11.2}; only length [0], length [1], length [2], and length [3] are initialized with the listed values. The other array elements will be initialized to zero. Unfortunately, there is no method of either indicating repetition of an initial- ization value or initializing later array elements without first specifying values for earlier elements. A unique feature of initializers is that the size of an array may be omitted when initializing values are included in the declaration statement. For example, the declaration int gallons[] = {16, 12, 10, 14, ll}; reserves enough storage room for five elements. Similarly, the following two dec- larations are equivalent: 251 char codes [6] = {' s " ' a I , char codes [] = {' s " 'a', 'm', 'pi, 1m', 'pi, I 1', '1' , 'e' }; I e I} ; Both of these declarations set aside six character locations for an array named codes. An interesting and useful simplification can also be used when initializ- ing character arrays. For example, the declaration char codes[] = "sample"; /* no braces or commas */ uses the string "sample" to initialize the codes array. Recall that a string is any sequence of characters enclosed in double quotes. This last declaration cre- ates an array named codes having seven elements and fills the array with the seven characters illustrated in Figure 6-6. The first six characters, as expected, consist of the letters s, a, m, p, 1,and e. The last character, which is the escape sequence \0, is called the null character. The null character is automatically appended to all strings by the C compiler. This character has an internal storage code that is numerically equal to zero (the storage code for the zero character has a numerical value of decimal 48, so the two cannot be confused by the com- puter), and is used as a marker, or sentinel, to mark the end of a string. As we shall see in Chapter 11, this marker is invaluable when manipulating strings of characters. Once values have been assigned to array elements, either through initializa- tion within the declaration statement, using the interactive input described in Section 6.1, or by assignment the array elements can be processed as described in FIGURE 6-6 A String Is Terminated with a Special Sentinel codes [0] codes [1] codes [2] codes [3] codes [4] codes[5] codes[6] Islalmlpl_lel\OI 252 Chapter Six Arrays the previous section. For example, Program 6-3 illustrates the initialization of array elements within the declaration of the array and then uses a for loop to locate the maximum value stored in the array. ,lql, Program 6-3 #include <stdio.h> main( ) { int i, max, nums[5] {2, 18, 1, 27, 16}; max = nums[O]; for (i = 1; i <= 4; ++i) if (max < nums[i]) max = nums[i]; printf ("The maximum value is %d", max); The output produced by Program 6-3is: The maximum value is 27 Exercises 6.2 1. Write array declarations, including initializers, for the following: a. a list of ten integer grades: 89, 75, 82, 93, 78, 95, 81, 88, 77, 82 b. a list of five double precision amounts: 10.62, 13.98, 18.45, 12.68, 14.76 c. a list of 100 double precision interest rates; the first six rates are 6.29, 6.95, 7.25, 7.35, 7.40,7.42 d. a list of 64 floating point temperatures; the first ten temperatures are 78.2, 69.6, 68.5, 83.9,55.4,67.0,49.8,58.3, 62.5, 71.6 e. a list of 15 character codes; the first seven codes are f, j, m, q, t, w, z 2. Write an array declaration statement that stores the following values in an array named volts: 16.24, 18.98,23.75,16.29,19.54,14.22,11.13,15.39. Include these statements in a program that displays the values in the array. 3. Write a program that uses an array declaration statement to initialize the following numbers in an array named slopes: 17.24,25.63,5.94,33.92,3.71,32.84,35.93,18.24,6.92. Your program should locate and display both the maximum and minimum values in the array. 4. Write a program that stores the following prices in an array named prices: 9.92, 6.32, 12.63,5.95,10.29. Your program should also create two arrays named units and amounts, each capable of storing five double precision numbers. Using a for loop and a scanf ( ) function call, have your program accept five user-input numbers into the units array when the program is run. Your program should store the product of the corresponding values in the prices and units arrays in the amounts array (for example, amounts [1] 6.3 Two-Dimensional Arrays prices [1] * units [1] ) and display the following output (fill in the table appropriately): 253 Price 9.92 6.32 12.63 5.95 10.29 Total: Units Amount 5. The string of characters "Good Morning" is to be stored in a character array named goodstrl. Write the declaration for this array in three different ways. 6 a. Write declaration statements to store the string of characters" Input the Following Data" in a character array named messag1, the string ,, " in the array named messag2, the string "Enter the Date: "in the array named messag3, and the string "Enter the Account Number: " in the array named messag4. b. Include the array declarations written in Exercise 6a in a program that uses the printf ( ) function to display the messages. For example, the statement printf ("%s", messag1) ; causes the string stored in the messag1 array to be displayed. Your program will require four such statements to display the four individual messages. Using the printf ( ) function with the %s control sequence to display a string requires that the end-of-string marker \0 is present in the character array used to store the string. 7 a. Write a declaration to store the string "This is a test" into an array named strtest. Include the declaration in a program to display the message using the following loop: for (i = 0; i <= 13; ++i) printf("%c", strtest[i]); b. Modify the for statement in Exercise 7a to display only the array characters t, e, s, and t. c. Include the array declaration written in Exercise 7a in a program that uses the printf ( ) function to display characters in the array. For example, the statement printf ("%s", strtest); will cause the string stored in the strtest array to be displayed. Using this statement requires that the last character in the array is the end-of- string marker \ o. d. Repeat Exercise 7a using a while loop. (Hint: Stop the loop when the \0 escape sequence is detected. The expression while (strtest [i] ! = '\0') can be used.) 6.3 Two-Dimensional Arrays A two-dimensional array, which is also referred to as a table, consists of both rows and columns of elements. For example, the array of numbers 8 16 9 52 3 15 27 6 14 25 2 10 254 ChapterSix Arrays is called a two-dimensional array of integers. This array consists of three rows and four columns. To reserve storage for this array, both the number of rows and the number of columns must be included in the array's declaration. Calling the array val, the correct specification for this two-dimensional array is: int val [3] [4]; Similarly, the declarations float volts [10] [5]; char code [6] [26]; declare that the array volts consists of 10 rows and 5 columns oHloating point numbers and that the array code consists of 6 rows and 26 columns, with each element capable of holding one character. In order to locate each element in a two-dimensional array, an element is identified by its position in the array. As illustrated in Figure 6-7, the term val [1] [3] uniquely identifies the element in row 1, column 3. As with one- dimensional array variables, double-dimensional array variables can be used anywhere scalar variables are valid. Examples using elements of the val array are: watts = val [2] [3]; val [0] [0] = 62; newnum = 4 * (val [1] [0] - 5); sum_row = val [0] [0] + val [0] [1] + val [0] [2] + val [0] [3]; The last statement causes the values of the four elements in row 0 to be added and the sum to be stored in the scalar variable sum_row. As with one-dimensional arrays, two-dimensional arrays can be initialized from within their declaration statements. This is done by listing the initial values within braces and separating them by commas. Additionally, braces can be used to separate individual rows. For example, the declaration int val[3] [4] = { {B,16,9,52}, {3,15,27,6}, {l4,25,2,10} }; FIGURE 6-7 Each Array Element Is Identified by Its Rowand Column Position Col.O Col.1 Col.2 Col.3 ~ ~ ~ ~ Row0 8 16 9 52 Row1 3 15 27 6 • val [1] [3] Row2 •. 14 25 2 10 / ~ Row Column position position ~.~ ~-~ -_., - ~-_._ 6.3 Two-Dimensional Arrays 255 Initialization starts with this element < < < < < J, val[l] [0] = 3 > val[l] [1] = 15 > val[l] [2] = 27 > val[l] [3] = 6 J, 1 va1[O] [0] = 8 > va1[O] [1] = 16 > va1[O] [2] = 9 > va1[O] [3] = 52 J, < < < < < J, val [2] [0] = 14 > val [2] [1] = 25 > va1[2] [2] = 2 > va1[2] [3] = 10 FIGURE 6-8 Storage and Initialization of the val[ ] array declares val to be an array of integers with three rows and four columns, with the initial values given in the declaration. The first set of internal braces contains the values for row 0 of the array, the second set of internal braces contains the values for row 1, and the third set of braces the values for row 2. Although the commas in the initialization braces are always required, the inner braces can be omitted. Thus, the initialization for val may be written as int val[3] [4] = {8,16,9,52, 3,15,27,6, 14,25,2,10}; The separation of initial values into rows in the declaration statement is not necessary since the compiler assigns values beginning with the [0] [0] element and proceeds row by row to fill in the remaining values. Thus, the initialization int val[3] [4] = {8,16,9,52,3,15,27,6,14,25,2,10}; is equally valid but does not clearly illustrate to another programmer where one row ends and another begins. . As illustrated in Figure 6-8, the initialization of a two-dimensional array is done in row order. First, the elements of the first row are initialized, then the ele- ments of the second row are initialized, and so on, until the initializations are completed. This row ordering is also the same ordering used to store two-dimen- sional arrays. That is, array element [0] [0] is stored first, followed by element [0] [1], followed by element [0] [2] and so on. Following the first row's ele- ments are the second row's elements, and so on for all the rows in the array. As with one-dimensional arrays, two-dimensional arrays may be displayed by individual element notation or by using loops (while, for, or do). This is illustrated by Program 6-4 (p. 256),which displays all the elements of a three-by- four two-dimensional array using two different techniques. Following is the display produced by Program 6-4: Display of val array by explicit element 8 16 9 52 3 15 27 6 14 25 2 10 256 Chapter Six Arrays JQI, Program 6-4 #include <stdio.h> main ( ) { int i, j, val [3] [4] {S,16,9,52, 3,15,27,6, 14,25,2,10}; printf("\nDisplay of val array by explicit element"); printf ("\n%2d %2d %2d %2d",val [0] [O],val [0] [1], val [0] [2],val [0] [3]); printf ("\n%2d %2d %2d %2d",val [1] [0] ,val [1] [1] ,val [1] [2] ,val[ 1] [3] ) ; printf("\n%2d %2d %2d %2d",val[2] [0],val[2] [1],val[2] [2],va1[2] [3]); printf("\n\nDisplay of val array using a nested for loop"); for (i = 0; i < 3; ++i) { printf (" \n") ; 1* print a new line for each row *1 for (j = 0; j < 4; ++j) printf ("%2d ", val [i] [j]); Display of val array using a nested for loop 8 16 9 52 3 15 27 6 14 25 2 10 The first display of the val array produced by Program 6-4 is constructed by explicitly designating each array element. The second display of array element values, which is identical to the first, is produced using a nested for loop. Nested loops are especially useful when dealing with two-dimensional arrays because they allow the programmer to easily designate and cycle through each element. In Program 6-4, the variable i controls the outer loop and the variable j controls the inner loop. Each pass through the outer loop corresponds to a single row, with the inner loop supplying the appropriate column elements. After a complete column is printed a new line is started for the next row. The effect is a display of the array in a row-by-row fashion. Once two-dimensional array elements have been assigned array processing can begin. Typically, for loops are used to process two-dimensional arrays because, as previously noted, they allow the programmer to easily designate and cycle through each array element. For example, the nested for loop illustrated in Program 6-5 is used to multiply each element in the val arrayby the scalar num- ber 10 and display the resulting value. Following is the output produced by Program 6-5: Display of multiplied elements 80 160 90 520 30 150 270 60 140 250 20 100 6.3 Two-Dimensional Arrays ,101, Program 6-5 257 #include <stdio.h> main( ) { int i, j, val[3] [4] {8,16,9,52, 3,15,27,6, 14,25,2,10}; /* multiply each element by 10 and display it */ printf("\n\nDisplay of multiplied elements\n"); for (i = 0; i < 3; ++i) { .printf("\n"); /* print a blank line */ for (j = 0; j < 4; ++j) '{ valli] [j] valli] [j] * 10; printf ("%3d ", val [i] [j]) ; /* end of inner loop */ /* end of outer loop */ Larger-Dimensional Arrays Although arrays with more than two dimensions are not commonly used, C does allow any number of dimensions to be declared. This is done by listing the maxi- mum size of all dimensions for the array. For example, the declaration int response [4] [10] [[6]; declares a three-dimensional array. The first ele- ment in the array is designated as response [0] [0] [0] and the last element asresponse [3] [9] [5]. Conceptually, as illustrated in Figure 6-9, a three-dimensional array can be FIGURE 6-9 Repres~ntation of a Three-Dimensional Array Row index Page number index 258 Chapter Six Arrays viewed as a book of data tables. Using this visualization, the first subscript can be thought of as the location of the desired row in a table, the second subscript value as the desired column, and the third subscript value, which is often called the "rank," as the page number of the selected table. Similarly, arrays of any dimension can be declared. Conceptually, a four- dimensional array can be represented as a shelf of books, where the fourth dimension is used to declare a desired book on the shelf, and a five-dimensional array can be viewed as a bookcase filled with books where the fifth dimension refers to a selected shelf in the bookcase. Using the same analogy, a six-dimen- sional array can be considered as a single row of bookcases where the sixth dimension references the desired bookcase in the row; a seven-dimensional array can be considered as multiple rows of bookcases where the seventh dimension references the desired row, and so on. Alternatively, arrays of three-, four-, five-, six-, etc. dimensional arrays can be viewed as mathematical n-tuples of order three, four, five, six, etc., respectively. Exercises 6.3 1. Write appropriate specification statements for: a. an array of integers with 6 rows and 10 columns b. an array of integers with 2 rows and 5 columns c. an array of characters with 7 rows and 12 columns d. an array of characters with 15 rows and 7 columns e. an array of floating point numbers with 10 rows and 25 columns f. an array of floating point numbers with 16 rows and 8 columns 2. Determine the output produced by the following program: #include <stdio.h> main ( ) { int i, j, val[3] [4] = {8,16,9,52,3,15,27,6,14,25,2,10}; for (i = 0; i < 3; ++i) for (j = 0; j < 4; ++j) printf ("%2d ", val [i] [j]); 3 a. Write a C program that adds the values of all elements in the val array used in Exercise 2 and displays the total. b. Modify the program written for Exercise 3a to display the total of each row separately. 4. Write a C program that adds equivalent elements of the two-dimensional arrays named first and second. Both arrays should have two rows and three columns. For example, element [1] [2] ofthe resulting array should be the sum of first [1] [2] and second [1] [2]. The first and second arrays should be initialized as follows: 16 54 FIRST 18 91 23 11 24 16 SECOND 52 .77 19 59 5 a. Write a C program that finds and displays the maximum value in a two-dimensional 6.4 Applications array of integers. The array should be declared as a four-by-five array of integers and initialized with these data: 16,22,99,4,18,-258,4,101,5,98,105,6,15,2,45,33,88,72,16,3 b. Modify the program written in Exercise Sa so that it also displays the maximum value's row and column subscript numbers. 6. Write a C program to select the values in a four-by-five array of integers in increasing order and store the selected values in the single-dimensional array named sort. Use the data given in Exercise Sa to initialize the two-dimensional array. 7 a. A professor has constructed a two-dimensional array of float numbers having 3 rows and 5 columns. This array currently contains the test grades of the students in the professor's advanced compiler design class. Write a C program that reads 15 array values and then determines the total number of grades in the ranges less than 60, greater than or equal to 60 and less than 70, greater than or equal to 70 and less than 80, greater than or equal to 80 and less than 90, and greater than or equal to 90. b. Entering 15 grades each time the program written for Exercise 7a is run is cumbersome. What method is appropriate for initializing the array during the testing phase? c. How might the program you wrote for Exercise 7a be modified to include the case of no grade being present? That is, what grade could be used to indicate an invalid grade and how would your program have to be modified to exclude counting such a grade? 6.4 Applications Arrays are extremely useful for plotting data on either a video screen or a stan- dard line printer. In this section we present a simple but elegant method of con- structing such plots. The first application presents the basic method and uses it to produce modest plots. The second application incorporates data scaling to ensure that the plot fits within the area of the video screen or paper, regardless of the range of data plotted. Application 1: Curve Plotting In graphing data on either a video screen or printer two basic constraints must be considered. The first constraint is that both devices automatically move in a for- ward direction, which means that our graphs should avoid the need to "back up" (although there are methods for reversing the cursor motion on a video screen, all of our programs will be constructed to work for both printers and screens). The second constraint is that both printer paper and video displays are restricted in the horizontal direction to displaying a maximum of either 80 or 132 charac- ters. No such restriction exists in the vertical direction because the paper length is effectively unlimited and the video display scrolls forward. For this reason our plots will always be constructed "sideways" with the y axis horizontal and the x axis vertical. With these two constraints in mind, consider the plot shown in Figure 6-10 (p. 260). As illustrated in Figure 6-10, the graph is plotted sideways with the y axis displayed across the top of the graph and the x axis displayed down the side. Omitting, for the moment, the two header lines, 259 260 Chapter Six Arrays y axis + > the actual graph of the data points consists of 15individual lines, as follows: line 1 : I * line 2 : I * line 3 : I * line 4 : I * line 5 : I * line 6 : I * line 7 : I * line 8 : I * line 9 : I * line 10: I * line 11: I * line 12: I * line 13: I * line 14: I * line 15: I * Notice that individually, each line consists of only two printed symbols, a bar ( I) and an asterisk (*). The bar is always displayed in column 1and the asterisk is positioned to indicate an appropriate y value. With these points in mind, it is rather easy to construct these 15 lines. To do this we will first construct an exact image of the first line to be printed in an array of characters. After the array is constructed and printed it will be used to construct an image of the second line. After the second image is displayed the same array is used to construct an image of the third line, and so on until all 15 lines have been displayed. To make sure that the elements in the array can be displayed on a page the array should be FIGURE 6-10 y axis + > I I I I I I * I * I * I * I * I I I I I * * * * * * * * * * [...]... in column 4 range from a to 53 , for a total range of 54 possible y values These values can be used directly by the curve plotting routine presented in the previous application to create a graph similar to that shown in Figure 6-14 6.4 2 65 Applications TABLE 6-1 Values of the Equation y x y -5. 0 -4 .5 -4.0 -3 .5 -3.0 -2 .5 -2.0 -1 .5 -1.0 -0 .5 0.0 0 .5 1.0 1 .5 2.0 2 .5 3.0 3 .5 4.0 4 .5 5.0 -1 25. 000 -91.1 25. .. Figure 6- 15 is closed at time t = 0, the voltage, V, across the capacitor is given by the equation V = E(l - et/(RC», where E is the voltage of the battery, R is the circuit resistance, C is the value of the capacitance, and t is in seconds Assuming that E = 50 , R = 4000, and C = 0 05, modify Program 6-7 to plot the voltage across the capacitor from t = 0 to t = 30, in increments of 1 second 6 Enter and run... on your computer system 7 Modify Program 6-8 to plot the voltage across the capacitor illustrated in Figure 6- 15 from t = 0 to t = 30 seconds in increments of 1 second For this problem assume that E = 100 volts, R = 4000, and C = 0 05 8 Figure 6-16 illustrates a harmonic oscillator, which consists of an object of mass M FIGURE 6- 15 A Simple RC Circuit + E FIGURE 6-16 r A Harmonic Oscillator 268 Chapter... function can be called Declaring a Function Before a function can be called, it must be declared to the function that will do the calling The declaration statement for a function is formally referred to as a function prototype The function prototype tells the calling function the type of value that will be returned, if any, and the data type of the values that the calling function should transmit to the called... function Each C function is a separate and independent entity with its own parameters and variables and must never be included within another function Standard Library Functions In addition to writing their own function, all C programmers have access to a standard, preprogrammed set of functions for handling input and output of data, computing mathematical quantities, and manipulating strings of characters... calling function name Thus, the function prototype for find_max ( ) could have been placed either before or after the statement #include , which contains the function prototypes for the printf ( ) and scanf ( ) functions called in main ( ) (Reasons for the choice of placement are presented in Section 7.4.) The general form of function prototype statements is: return-data-type function-name(list... referred to as the calling function The terms called and calling come from standard telephone usage, where one party calls the other on a telephone The party initiating the call is referred to as the calling party, and the party receiving the call is referred to as the called party The same terms describe function calls Within main ( ) the FIGURE 7-1 Calling and Passing Data to a Function function_name(data... ); causes the next character entered at the terminal to be stored in the variable in_char This is equivalent to the longer statement scanf ( "%d", &in_char) ; The getchar ( ) routine is extremely useful when continuously inputting strings of characters, which is the topic of Chapter 11 The output library function corresponding to getchar ( ) is the putchar ( ) function The putchar ( ) function expects... Exercises for Chapter 6 1 Enter and run Program 6-7 on your computer system 2 Modify Program 6-7 to plot the curve y = x3 - 4 Y! + 3x + 2 for x equal to 0,1,2,3,4 ,5, and 6 3 Modify Program 6-7 to plot the curve y = x3 - 4 Y! + 3x + 2 for x between -8 and +8, in increments of 0 .5 4 Modify Program 6-7 to plot the curve y = 4x3 - x4 for x between -10 and + 10, in increments of 0 .5 5 When the switch illustrated... 2 with W = 54 , and using the correct minimum and maximum values of -1 25 and 1 25, respectively, yields the values listed in column 3 of the table Notice that the minimum value of -1 25 is converted to the value 0.000 and the maximum value of 1 25 is converted to the value 53 .000 The last column in the table gives the rounded and integerized values of the scaled-numbers listed in the third column Notice . last character, which is the escape sequence , is called the null character. The null character is automatically appended to all strings by the C compiler. This character has an internal storage code. 26.473 26 0.0 0.000 26 .50 0 27 0 .5 0.1 25 26 .52 7 27 1.0 1.000 26.712 27 1 .5 3.3 75 27.216 27 2.0 8.000 28.196 28 2 .5 15. 6 25 29.813 30 3.0 27.000 32.224 32 3 .5 42.8 75 35. 590 36 4.0 64.000 40.068 40 4 .5 91.1 25 45. 819 46 5. 0 1 25. 000 53 .000 53 FIGURE 6-14 Minimum. 7.186 7 -4.0 -64.000 12.932 13 -3 .5 -42.8 75 17.411 17 -3.0 -27.000 20.776 21 -2 .5 - 15. 6 25 23.188 23 -2.0 -8.000 24.804 25 -1 .5 -3.3 75 25. 786 26 -1.0 -1.000 26.288 26 -0 .5 -0.1 25 26.473 26 0.0 0.000 26 .50 0 27 0 .5 0.1 25 26 .52 7 27 1.0 1.000 26.712 27 1 .5 3.375

Ngày đăng: 12/08/2014, 09:22

Từ khóa liên quan

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

Tài liệu liên quan