0% found this document useful (0 votes)
12 views80 pages

Week 6

Uploaded by

bewahig513
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views80 pages

Week 6

Uploaded by

bewahig513
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 80

Week 6

Arrays
C How to Program, 8/e, GE

© 2016 Pearson Education, Ltd. All rights reserved. 1


© 2016 Pearson Education, Ltd. All rights reserved. 2
6.2 Arrays

• An array is a group of contiguous memory locations that all have the


same type.
• To refer to a particular location or element in the array, we specify the
array’s name and the position number of the particular element in the
array.
• Figure 6.1 shows an integer array called c, containing 12 elements.
• Any one of these elements may be referred to by giving the array’s
name followed by the position number of the particular element in
square brackets ([]).

© 2016 Pearson Education, Ltd. All rights reserved. 3


© 2016 Pearson Education, Ltd. All rights reserved. 4
6.2 Arrays (Cont.)

• The first element in every array is the zeroth element.


• An array name, like other identifiers, can contain only letters, digits and
underscores and cannot begin with a digit.
• The position number within square brackets is called an index or subscript.
• An index must be an integer or an integer expression.

© 2016 Pearson Education, Ltd. All rights reserved. 5


6.2 Arrays (Cont.)

• For example, if a = 5 and b = 6, then the statement


• c[a + b] += 2;
• adds 2 to array element c[11].
• An indexed array name is an lvalue—it can be used on the left side of
an assignment.

© 2016 Pearson Education, Ltd. All rights reserved. 6


6.2 Arrays (Cont.)

• Let’s examine array c (Fig. 6.1) more closely.


• The array’s name is c.
• Its 12 elements are referred to as c[0], c[1], c[2], …, c[10] and c[11].
• The value stored in c[0] is –45, the value of c[1] is 6, c[2] is 0, c[7] is
62 and c[11] is 78.
• To print the sum of the values contained in the first three elements of array c,
we’d write
• printf("%d", c[0] + c[1] + c[2]);
• To divide the value of element 7 of array c by 2 and assign the result to the
variable x, write

© 2016 Pearson Education, Ltd. All rights reserved. 7


6.2 Arrays (Cont.)

• The brackets used to enclose the index of an array are actually


considered to be an operator in C.
• They have the same level of precedence as the function call operator
(i.e., the parentheses that are placed after a function name to call
that function).
• Figure 6.2 shows the precedence and associativity of the operators
introduced to this point in the text.

© 2016 Pearson Education, Ltd. All rights reserved. 8


© 2016 Pearson Education, Ltd. All rights reserved. 9
6.3 Defining Arrays

• Arrays occupy space in memory.


• You specify the type of each element and the number of elements
each array requires so that the computer may reserve the appropriate
amount of memory.
• The following definition reserves 12 elements for integer array c,
which has indices in the range 0-11.
• int c[12];

© 2016 Pearson Education, Ltd. All rights reserved. 10


6.3 Defining Arrays (Cont.)

• The definition
• int b[100], x[27];
reserves 100 elements for integer array b and 27 elements for integer
array x.
• These arrays have indices in the ranges 0–99 and 0–26, respectively.
• Arrays may contain other data types.
• Character strings and their similarity to arrays are discussed in
Chapter 8. The relationship between pointers and arrays is discussed
in Chapter 7.

© 2016 Pearson Education, Ltd. All rights reserved. 11


6.4 Array Examples

6.4.1 Defining an Array and Using a Loop to Set the Array’s Element
Values
• Like any other variables, uninitialized array elements contain garbage
values.
• Figure 6.3 uses for statements to initialize the elements of a five
integer array n to zeros and print the array in tabular format.
• The first printf statement displays the column heads for the two
columns printed in the subsequent for statement.

© 2016 Pearson Education, Ltd. All rights reserved. 12


© 2016 Pearson Education, Ltd. All rights reserved. 13
© 2016 Pearson Education, Ltd. All rights reserved. 14
6.4 Array Examples (Cont.)

• Notice that the variable i is declared to be of type size_t, which


according to the C standard represents an unsigned integral type.
• This type is recommended for any variable that represents an array’s
size or an array’s indices.
• Type size_t is defined in header <stddef.h>, which is often
included by other headers (such as <stdio.h>).
• [Note: If you attempt to compile Fig. 6.3 and receive errors, simply
include <stddef.h> in your program.]

© 2016 Pearson Education, Ltd. All rights reserved. 15


6.4 Array Examples (Cont.)

Initializing an Array in a Definition with an Initializer List


• The elements of an array can also be initialized when the array is
defined by following the definition with an equals sign and braces,
{}, containing a comma-separated list of array initializers.
• Figure 6.4 initializes an integer array with five values and prints the
array in tabular format.

© 2016 Pearson Education, Ltd. All rights reserved. 16


© 2016 Pearson Education, Ltd. All rights reserved. 17
© 2016 Pearson Education, Ltd. All rights reserved. 18
6.4 Array Examples (Cont.)

• If there are fewer initializers than elements in the array, the remaining
elements are initialized to zero.
• For example, the elements of the array n in Fig. 6.3 could have been
initialized to zero as follows:
// initializes entire array to zeros
int n[10] = {0};
• This explicitly initializes the first element to zero and initializes the
remaining nine elements to zero because there are fewer initializers
than there are elements in the array.

© 2016 Pearson Education, Ltd. All rights reserved. 19


6.4 Array Examples (Cont.)

• It’s important to remember that arrays are not automatically


initialized to zero.
• You must at least initialize the first element to zero for the remaining
elements to be automatically zeroed.

© 2016 Pearson Education, Ltd. All rights reserved. 20


© 2016 Pearson Education, Ltd. All rights reserved. 21
6.4 Array Examples (Cont.)

• The array definition


• int n[5] = {32, 27, 64, 18, 95, 14};
causes a syntax error because there are six initializers and only five
array elements.

© 2016 Pearson Education, Ltd. All rights reserved. 22


6.4 Array Examples (Cont.)

• If the array size is omitted from a definition with an initializer list, the
number of elements in the array will be the number of elements in
the initializer list.
• For example,
• int n[] = {1, 2, 3, 4, 5};
would create a five-element array initialized with the indicated values.

© 2016 Pearson Education, Ltd. All rights reserved. 23


6.4 Array Examples (Cont.)

Specifying an Array’s Size with a Symbolic Constant and Initializing


Array Elements with Calculations
• Figure 6.5 initializes the elements of a 5-element array s to the values
2, 4, 6, 8, 10 and prints the array in tabular format.
• The values are generated by multiplying the loop counter by 2 and
adding 2.

© 2016 Pearson Education, Ltd. All rights reserved. 24


© 2016 Pearson Education, Ltd. All rights reserved. 25
© 2016 Pearson Education, Ltd. All rights reserved. 26
6.4 Array Examples (Cont.)

• The #define preprocessor directive is introduced in this program.


• #define SIZE 5
• defines a symbolic constant SIZE whose value is 5.
• A symbolic constant is an identifier that’s replaced with replacement
text by the C preprocessor before the program is compiled.

© 2016 Pearson Education, Ltd. All rights reserved. 27


6.4 Array Examples (Cont.)

• When the program is preprocessed, all occurrences of the symbolic


constant SIZE are replaced with the replacement text 5.
• Using symbolic constants to specify array sizes makes programs more
modifiable.
• In Fig. 6.5, we could have the first for loop fill a 1000-element array
by simply changing the value of SIZE in the #define directive from
5 to 1000.
• If the symbolic constant SIZE had not been used, we’d have to
change the program in three separate places.

© 2016 Pearson Education, Ltd. All rights reserved. 28


© 2016 Pearson Education, Ltd. All rights reserved. 29
© 2016 Pearson Education, Ltd. All rights reserved. 30
© 2016 Pearson Education, Ltd. All rights reserved. 31
© 2016 Pearson Education, Ltd. All rights reserved. 32
© 2016 Pearson Education, Ltd. All rights reserved. 33
6.4 Array Examples (Cont.)

Summing the Elements of an Array


• Figure 6.6 sums the values contained in the 12-element integer array
a.
• The for statement’s body does the totaling.

© 2016 Pearson Education, Ltd. All rights reserved. 34


© 2016 Pearson Education, Ltd. All rights reserved. 35
6.4 Array Examples (Cont.)

Using Arrays to Summarize Survey Results


• Our next example uses arrays to summarize the results of data
collected in a survey.
• Consider the problem statement.
• Forty students were asked to rate the quality of the food in the student
cafeteria on a scale of 1 to 10 (1 means awful and 10 means excellent). Place
the 40 responses in an integer array and summarize the results of the poll.
• This is a typical array application (see Fig. 6.7).
• We wish to summarize the number of responses of each type (i.e., 1
through 10).
© 2016 Pearson Education, Ltd. All rights reserved. 36
© 2016 Pearson Education, Ltd. All rights reserved. 37
© 2016 Pearson Education, Ltd. All rights reserved. 38
6.4 Array Examples (Cont.)

• The array responses is a 40-element array of the students’


responses.
• We use an 11-element array frequency to count the number of
occurrences of each response.
• We ignore frequency[0] because it’s logical to have response 1
increment frequency[1] rather than frequency[0].
• This allows us to use each response directly as the index in the
frequency array.

© 2016 Pearson Education, Ltd. All rights reserved. 39


6.4 Array Examples (Cont.)

• The for loop takes the responses one at a time from the array
responses and increments one of the 10 counters
(frequency[1] to frequency[10]) in the frequency array.
• The key statement in the loop is
• ++frequency[responses[answer]];
which increments the appropriate frequency counter depending
on the value of responses[answer].

© 2016 Pearson Education, Ltd. All rights reserved. 40


6.4 Array Examples (Cont.)

• When the counter variable answer is 0, responses[answer] is


1, so ++frequency[responses[answer]]; is interpreted as
• ++frequency[1];
which increments array element one.
• When answer is 1, responses[answer] is 2, so +
+frequency[responses[answer]]; is interpreted as
• ++frequency[2];
which increments array element two.

© 2016 Pearson Education, Ltd. All rights reserved. 41


6.4 Array Examples (Cont.)

• When answer is 2, responses[answer] is 6, so +


+frequency[responses[answer]]; is interpreted as
• ++frequency[6];
which increments array element six, and so on.
• Regardless of the number of responses processed in the survey, only
an 11-element array is required (ignoring element zero) to summarize
the results.
• If the data contained invalid values such as 13, the program would
attempt to add 1 to frequency[13].
• This would be outside the bounds of the array.
© 2016 Pearson Education, Ltd. All rights reserved. 42
6.4 Array Examples (Cont.)

• C has no array bounds checking to prevent the program from referring


to an element that does not exist.
• Thus, an executing program can “walk off” either end of an array
without warning—a security problem that we discuss in Section 6.11.
• You should ensure that all array references remain within the bounds
of the array.

© 2016 Pearson Education, Ltd. All rights reserved. 43


© 2016 Pearson Education, Ltd. All rights reserved. 44
© 2016 Pearson Education, Ltd. All rights reserved. 45
6.4 Array Examples (Cont.)

Graphing Array Element Values with Histograms


• Our next example (Fig. 6.8) reads numbers from an array and graphs
the information in the form of a bar chart or histogram—each
number is printed, then a bar consisting of that many asterisks is
printed beside the number.
• The nested for statement draws the bars.
• Note the use of puts("") to end each histogram bar.

© 2016 Pearson Education, Ltd. All rights reserved. 46


© 2016 Pearson Education, Ltd. All rights reserved. 47
© 2016 Pearson Education, Ltd. All rights reserved. 48
6.4 Array Examples (Cont.)

Rolling a Die 60,000,000 Times and Summarizing the Results in an


Array
• Roll a single six-sided die 60,000,000 times to test whether the
random number generator actually produces random numbers.
• An array version of this program is shown in Fig. 6.9.

© 2016 Pearson Education, Ltd. All rights reserved. 49


© 2016 Pearson Education, Ltd. All rights reserved. 50
© 2016 Pearson Education, Ltd. All rights reserved. 51
6.5 Using Character Arrays to Store and Manipulate
Strings
• We now discuss storing strings in character arrays.
• So far, the only string-processing capability we have is outputting a
string with printf.
• A string such as "hello" is really an array of individual characters in
C.
• A character array can be initialized using a string literal.
• For example,
• char string1[] = "first";
initializes the elements of array string1 to the individual characters
in the string literal "first".
© 2016 Pearson Education, Ltd. All rights reserved. 52
6.5 Using Character Arrays to Store and Manipulate
Strings
• In this case, the size of array string1 is determined by the compiler based
on the length of the string.
• The string "first" contains five characters plus a special string-termination
character called the null character.
• Thus, array string1 actually contains six elements.
• The character constant representing the null character is '\0'.
• All strings in C end with this character.
• A character array representing a string should always be defined large enough
to hold the number of characters in the string and the terminating null
character.
• Character arrays also can be initialized with individual character constants in
an initializer list, but this can be tedious.
© 2016 Pearson Education, Ltd. All rights reserved. 53
6.5 Using Character Arrays to Store and Manipulate
Strings
• The preceding definition is equivalent to
• char string1[] =
{'f', 'i', 'r', 's', 't', '\0'};
• Because a string is really an array of characters, we can access
individual characters in a string directly using array index notation.
• For example, string1[0] is the character 'f' and string1[3]
is the character 's'.
• We also can input a string directly into a character array from the
keyboard using scanf and the conversion specifier %s.

© 2016 Pearson Education, Ltd. All rights reserved. 54


6.5 Using Character Arrays to Store and Manipulate
Strings
• For example,
• char string2[20];
creates a character array capable of storing a string of at most 19 characters
and a terminating null character.
• The statement
• scanf("%19s", string2);
reads a string from the keyboard into string2.
• The name of the array is passed to scanf without the preceding & used with
nonstring variables.
• The & is normally used to provide scanf with a variable’s location in memory
so that a value can be stored there.
© 2016 Pearson Education, Ltd. All rights reserved. 55
6.5 Using Character Arrays to Store and Manipulate
Strings
• Function scanf will read characters until a space, tab, newline or end-of-file
indicator is encountered.
• The string2 should be no longer than 19 characters to leave room for the
terminating null character.
• If the user types 20 or more characters, your program may crash or create a
security vulerability.
• For this reason, we used the conversion specifier %19s so that scanf reads a
maximum of 19 characters and does not write characters into memory beyond
the end of the array string2.

© 2016 Pearson Education, Ltd. All rights reserved. 56


6.5 Using Character Arrays to Store and Manipulate
Strings
• It’s your responsibility to ensure that the array into which the string is
read is capable of holding any string that the user types at the
keyboard.
• Function scanf does not check how large the array is.
• Thus, scanf can write beyond the end of the array.

© 2016 Pearson Education, Ltd. All rights reserved. 57


6.5 Using Character Arrays to Store and Manipulate
Strings
• A character array representing a string can be output with printf
and the %s conversion specifier.
• The array string2 is printed with the statement
• printf("%s\n", string2);
• Function printf, like scanf, does not check how large the
character array is.
• The characters of the string are printed until a terminating null
character is encountered.

© 2016 Pearson Education, Ltd. All rights reserved. 58


6.5 Using Character Arrays to Store and Manipulate
Strings
• Figure 6.10 demonstrates initializing a character array with a string
literal, reading a string into a character array, printing a character
array as a string and accessing individual characters of a string.

© 2016 Pearson Education, Ltd. All rights reserved. 59


© 2016 Pearson Education, Ltd. All rights reserved. 60
© 2016 Pearson Education, Ltd. All rights reserved. 61
6.11 Multidimensional Arrays

• Arrays in C can have multiple indices.


• A common use of multidimensional arrays is to represent tables of
values consisting of information arranged in rows and columns.
• To identify a particular table element, we must specify two indices:
The first (by convention) identifies the element’s row and the second
(by convention) identifies the element’s column.
• Tables or arrays that require two indices to identify a particular
element are called two-dimensional arrays.

© 2016 Pearson Education, Ltd. All rights reserved. 62


6.11 Multidimensional Arrays (Cont.)

• Multidimensional arrays can have more than two indices.


• Figure 6.20 illustrates a two-dimensional array, a.
• The array contains three rows and four columns, so it’s said to be a 3-
by-4 array.
• In general, an array with m rows and n columns is called an m-by-n
array

© 2016 Pearson Education, Ltd. All rights reserved. 63


© 2016 Pearson Education, Ltd. All rights reserved. 64
6.11 Multidimensional Arrays (Cont.)

• Every element in array a is identified in Fig. 6.20 by an element name


of the form a[i][j]; a is the name of the array, and i and j are
the indices that uniquely identify each element in a.
• The names of the elements in row 0 all have a first index of 0; the
names of the elements in column 3 all have a second index of 3.

© 2016 Pearson Education, Ltd. All rights reserved. 65


© 2016 Pearson Education, Ltd. All rights reserved. 66
6.11 Multidimensional Arrays (Cont.)

• A multidimensional array can be initialized when it’s defined, much like a one-
dimensional array.
• For example, a two-dimensional array int b[2][2] could be defined and
initialized with
• int b[2][2] = {{1, 2}, {3, 4}};
• The values are grouped by row in braces.
• The values in the first set of braces initialize row 0 and the values in the
second set of braces initialize row 1.
• So, the values 1 and 2 initialize elements b[0][0] and b[0][1],
respectively, and the values 3 and 4 initialize elements b[1][0] and b[1]
[1], respectively.
© 2016 Pearson Education, Ltd. All rights reserved. 67
6.11 Multidimensional Arrays (Cont.)

• If there are not enough initializers for a given row, the remaining
elements of that row are initialized to 0.
• Thus,
• int b[2][2] = {{1}, {3, 4}};
would initialize b[0][0] to 1, b[0][1] to 0, b[1][0] to 3 and
b[1][1] to 4.
• Figure 6.21 demonstrates defining and initializing two-dimensional
arrays.

© 2016 Pearson Education, Ltd. All rights reserved. 68


© 2016 Pearson Education, Ltd. All rights reserved. 69
© 2016 Pearson Education, Ltd. All rights reserved. 70
6.11 Multidimensional Arrays (Cont.)

• The program defines three arrays of two rows and three columns (six
elements each).
• The definition of array1 provides six initializers in two sublists.
• The first sublist initializes row 0 of the array to the values 1, 2 and 3;
and the second sublist initializes row 1 of the array to the values 4, 5
and 6.

© 2016 Pearson Education, Ltd. All rights reserved. 71


6.11 Multidimensional Arrays (Cont.)

• If the braces around each sublist are removed from the array1 initializer list,
the compiler initializes the elements of the first row followed by the elements
of the second row.
• The definition of array2 provides five initializers.
• The initializers are assigned to the first row, then the second row.
• Any elements that do not have an explicit initializer are initialized to zero
automatically, so array2[1][2] is initialized to 0.
• The definition of array3 provides three initializers in two sublists.

© 2016 Pearson Education, Ltd. All rights reserved. 72


6.11 Multidimensional Arrays (Cont.)

• The sublist for the first row explicitly initializes the first two elements of the
first row to 1 and 2.
• The third element is initialized to zero.
• The sublist for the second row explicitly initializes the first element to 4.
• The last two elements are initialized to zero.
• The program calls printArray to output each array’s elements.
• The function definition specifies the array parameter as const int a[][3].
• When we receive a one-dimensional array as a parameter, the array brackets
are empty in the function’s parameter list.

© 2016 Pearson Education, Ltd. All rights reserved. 73


6.11 Multidimensional Arrays (Cont.)

• The first index of a multidimensional array is not required either, but all
subsequent indices are required.
• The compiler uses these indices to determine the locations in memory of
elements in multidimensional arrays.
• All array elements are stored consecutively in memory regardless of the
number of indices.
• In a two-dimensional array, the first row is stored in memory followed by the
second row.
• Providing the index values in a parameter declaration enables the compiler to
tell the function how to locate an element in the array.

© 2016 Pearson Education, Ltd. All rights reserved. 74


6.11 Multidimensional Arrays (Cont.)

• In a two-dimensional array, each row is basically a one-dimensional


array.
• To locate an element in a particular row, the compiler must know how
many elements are in each row so that it can skip the proper number
of memory locations when accessing the array.
• Thus, when accessing a[1][2] in our example, the compiler knows
to skip the three elements of the first row to get to the second row
(row 1).
• Then, the compiler accesses element 2 of that row.

© 2016 Pearson Education, Ltd. All rights reserved. 75


6.11 Multidimensional Arrays (Cont.)

• Many common array manipulations use for iteration statements.


• For example, the following statement sets all the elements in row 2 of
array a in Fig. 6.20 to zero:
• for (size_t column = 0; column <= 3; ++column) {
a[2][column] = 0;
}
• We specified row 2, so the first index is always 2.

© 2016 Pearson Education, Ltd. All rights reserved. 76


6.11 Multidimensional Arrays (Cont.)

• The loop varies only the second index.


• The preceding for statement is equivalent to the assignment
statements:
• a[2][0] = 0;
a[2][1] = 0;
a[2][2] = 0;
a[2][3] = 0;

© 2016 Pearson Education, Ltd. All rights reserved. 77


6.11 Multidimensional Arrays (Cont.)

• The following nested for statement determines the total of all the
elements in array a.
• total = 0;
• for (size_t row = 0; row <= 2; ++row) {
for (size_t column = 0; column <= 3; ++column) {
total += a[row][column];
}
}
• The for statement totals the elements of the array one row at a
time.

© 2016 Pearson Education, Ltd. All rights reserved. 78


6.11 Multidimensional Arrays (Cont.)

• The outer for statement begins by setting row (i.e., the row index)
to 0 so that the elements of that row may be totaled by the inner
for statement.
• The outer for statement then increments row to 1, so the elements
of that row can be totaled.
• Then, the outer for statement increments row to 2, so the elements
of the third row can be totaled.
• When the nested for statement terminates, total contains the sum
of all the elements in the array a.

© 2016 Pearson Education, Ltd. All rights reserved. 79


© 2016 Pearson Education, Ltd. All rights reserved. 80

You might also like