1 of 93

6

C Arrays

1

© 2007 Pearson Education, Inc. All rights reserved.

2 of 93

Now go, write it before them in a table,�and note it in a book.

    • Isaiah 30:8

To go beyond is as wrong as to fall short.

    • Confucius

Begin at the beginning, …�and go on till you come to the end: then stop.

    • Lewis Carroll

2

© 2007 Pearson Education, Inc. All rights reserved.

3 of 93

OBJECTIVES

In this chapter you will learn:

  • To use the array data structure to represent lists and tables of values.
  • To define an array, initialize an array and refer to individual elements of an array.
  • To define symbolic constants.
  • To pass arrays to functions.
  • To use arrays to store, sort and search lists and tables of values.
  • To define and manipulate multiple-subscripted arrays.

3

© 2007 Pearson Education, Inc. All rights reserved.

4 of 93

6.1 Introduction

6.2 Arrays

6.3 Defining Arrays

6.4 Array Examples

6.5 Passing Arrays to Functions

6.6 Sorting Arrays

6.7 Case Study: Computing Mean, Median and Mode Using Arrays

6.8 Searching Arrays

6.9 Multiple-Subscripted Arrays

4

© 2007 Pearson Education, Inc. All rights reserved.

5 of 93

6.1 Introduction

  • Arrays
    • Structures of related data items
    • Static entity – same size throughout program
    • Dynamic data structures discussed in Chapter 12

5

© 2007 Pearson Education, Inc. All rights reserved.

6 of 93

6.2 Arrays

  • Array
    • Group of consecutive memory locations
    • Same name and type
  • To refer to an element, specify
    • Array name
    • Position number
  • Format:

arrayname[ position number ]

    • First element at position 0
    • n element array named c:
      • c[ 0 ], c[ 1 ]...c[ n – 1 ]

6

© 2007 Pearson Education, Inc. All rights reserved.

7 of 93

Fig. 6.1 | 12-element array.

7

© 2007 Pearson Education, Inc. All rights reserved.

8 of 93

6.2 Arrays

  • Array elements are like normal variables

c[ 0 ] = 3;

printf( "%d", c[ 0 ] );

    • Perform operations in subscript. If x equals 3

c[ 5 - 2 ] == c[ 3 ] == c[ x ]

8

© 2007 Pearson Education, Inc. All rights reserved.

9 of 93

Common Programming Error 6.1

It is important to note the difference between the “seventh element of the array” and “array element seven.” Because array subscripts begin at 0, the “seventh element of the array” has a subscript of 6, while “array element seven” has a subscript of 7 and is actually the eighth element of the array. This is a source of “off-by-one” errors.

9

© 2007 Pearson Education, Inc. All rights reserved.

10 of 93

10

Fig. 6.2 | Operator precedence.

© 2007 Pearson Education, Inc. All rights reserved.

11 of 93

6.3 Defining Arrays

  • When defining arrays, specify
    • Name
    • Type of array
    • Number of elements

arrayType arrayName[ numberOfElements ];

    • Examples:

int c[ 10 ];

float myArray[ 3284 ];

  • Defining multiple arrays of same type
    • Format similar to regular variables
    • Example:

int b[ 100 ], x[ 27 ];

11

© 2007 Pearson Education, Inc. All rights reserved.

12 of 93

6.4 Array Examples

  • Initializers

int n[ 5 ] = { 1, 2, 3, 4, 5 };

    • If not enough initializers, rightmost elements become 0

int n[ 5 ] = { 0 }

      • All elements 0
    • If too many initializers, a syntax error occurs
    • C arrays have no bounds checking
  • If size omitted, initializers determine it

int n[ ] = { 1, 2, 3, 4, 5 };

    • 5 initializers, therefore 5 element array

12

© 2007 Pearson Education, Inc. All rights reserved.

13 of 93

13

Outline

fig06_03.c

(1 of 2 )

for loop initializes each array element separately

for loop outputs all array elements

© 2007 Pearson Education, Inc. All rights reserved.

14 of 93

14

Outline

fig06_03.c

(2 of 2 )

© 2007 Pearson Education, Inc. All rights reserved.

15 of 93

15

Outline

fig06_04.c

(1 of 2 )

initializer list initializes all array elements simultaneously

© 2007 Pearson Education, Inc. All rights reserved.

16 of 93

16

Outline

fig06_04.c

(2 of 2 )

© 2007 Pearson Education, Inc. All rights reserved.

17 of 93

Common Programming Error 6.2

Forgetting to initialize the elements of an�array whose elements should be initialized.

17

© 2007 Pearson Education, Inc. All rights reserved.

18 of 93

Common Programming Error 6.3

Providing more initializers in an array�initializer list than there are elements�in the array is a syntax error.

18

© 2007 Pearson Education, Inc. All rights reserved.

19 of 93

19

Outline

fig06_05.c

(1 of 2 )

#define directive tells compiler to replace all instances of the word SIZE with 10

SIZE is replaced with 10 by the compiler, so array s has 10 elements

for loop initializes each array element separately

© 2007 Pearson Education, Inc. All rights reserved.

20 of 93

20

Outline

fig06_05.c

(2 of 2 )

© 2007 Pearson Education, Inc. All rights reserved.

21 of 93

Common Programming Error 6.4

Ending a #define or #include preprocessor directive with a semicolon. Remember that preprocessor directives are not C statements.

21

© 2007 Pearson Education, Inc. All rights reserved.

22 of 93

Common Programming Error 6.5

Assigning a value to a symbolic constant in�an executable statement is a syntax error.�A symbolic constant is not a variable. No�space is reserved for it by the compiler as with variables that hold values at execution time.

22

© 2007 Pearson Education, Inc. All rights reserved.

23 of 93

Software Engineering Observation 6.1

Defining the size of each array as a symbolic constant makes programs more scalable.

23

© 2007 Pearson Education, Inc. All rights reserved.

24 of 93

Good Programming Practice 6.1

Use only uppercase letters for symbolic constant names. This makes these constants stand out in a program and reminds you that symbolic constants are not variables.

24

© 2007 Pearson Education, Inc. All rights reserved.

25 of 93

Good Programming Practice 6.2

In multiword symbolic constant names, use underscores to separate the words for readability.

25

© 2007 Pearson Education, Inc. All rights reserved.

26 of 93

26

Outline

fig06_06.c

initializer list initializes all array elements simultaneously

for loop adds each element of the array to variable total

© 2007 Pearson Education, Inc. All rights reserved.

27 of 93

27

Outline

fig06_07.c

(1 of 2 )

#define directives create symbolic constants

frequency array is defined with 11 elements

responses array is defined with 40 elements and its elements are initialized

subscript of frequency array is given by value in responses array

© 2007 Pearson Education, Inc. All rights reserved.

28 of 93

28

Outline

fig06_07.c

(2 of 2 )

© 2007 Pearson Education, Inc. All rights reserved.

29 of 93

Good Programming Practice 6.3

Strive for program clarity. Sometimes it may be worthwhile to trade off the most efficient use of memory or processor time in favor of writing clearer programs.

29

© 2007 Pearson Education, Inc. All rights reserved.

30 of 93

Performance Tip 6.1

Sometimes performance considerations�far outweigh clarity considerations.

30

© 2007 Pearson Education, Inc. All rights reserved.

31 of 93

Common Programming Error 6.6

Referring to an element outside the array bounds.

31

© 2007 Pearson Education, Inc. All rights reserved.

32 of 93

Error-Prevention Tip 6.1

When looping through an array, the array subscript should never go below 0 and should always be less than the total number of elements in the array (size – 1). Make sure the loop-terminating condition prevents accessing elements outside this range.

32

© 2007 Pearson Education, Inc. All rights reserved.

33 of 93

Error-Prevention Tip 6.2

Programs should validate the correctness of all input values to prevent erroneous information from affecting a program’s calculations.

33

© 2007 Pearson Education, Inc. All rights reserved.

34 of 93

34

Outline

fig06_08.c

(1 of 2 )

nested for loop prints n[ i ] asterisks on the ith line

© 2007 Pearson Education, Inc. All rights reserved.

35 of 93

35

Outline

fig06_08.c

(2 of 2 )

© 2007 Pearson Education, Inc. All rights reserved.

36 of 93

36

Outline

fig06_09.c

(1 of 2 )

for loop uses one array to track number of times each number is rolled instead of using 6 variables and a switch statement

© 2007 Pearson Education, Inc. All rights reserved.

37 of 93

37

Outline

fig06_09.c

(2 of 2 )

© 2007 Pearson Education, Inc. All rights reserved.

38 of 93

6.4 Array Examples

  • Character arrays
    • String “first” is really a static array of characters
    • Character arrays can be initialized using string literals

char string1[] = "first";

      • Null character '\0' terminates strings
      • string1 actually has 6 elements

It is equivalent to

char string1[] = { 'f', 'i', 'r', 's', 't', '\0' };

    • Can access individual characters

string1[ 3 ] is character ‘s’

    • Array name is address of array, so & not needed for scanf

scanf( "%s", string2 );

      • Reads characters until whitespace encountered
      • Be careful not to write past end of array, as it is possible to do so

38

© 2007 Pearson Education, Inc. All rights reserved.

39 of 93

Common Programming Error 6.7

Not providing scanf with a character array large enough to store a string typed at the keyboard can result in destruction of data in a program and other runtime errors. This can also make a system susceptible to worm and virus attacks.

39

© 2007 Pearson Education, Inc. All rights reserved.

40 of 93

40

Outline

fig06_10.c

(1 of 2 )

string2 array is defined with one element for each character, so 15 elements including null character /0

for loop prints characters of string1 array with spaces in between

© 2007 Pearson Education, Inc. All rights reserved.

41 of 93

41

Outline

fig06_10.c

(2 of 2 )

© 2007 Pearson Education, Inc. All rights reserved.

42 of 93

Performance Tip 6.2

In functions that contain automatic arrays where the function is in and out of scope frequently, make the array static so it is not created each time the function is called.

42

© 2007 Pearson Education, Inc. All rights reserved.

43 of 93

43

Outline

fig06_11.c

(1 of 4 )

© 2007 Pearson Education, Inc. All rights reserved.

44 of 93

44

Outline

fig06_11.c

(2 of 4 )

static array is created only once, when staticArrayInit is first called

© 2007 Pearson Education, Inc. All rights reserved.

45 of 93

45

Outline

fig06_11.c

(3 of 4 )

automatic array is recreated every time automaticArrayInit is called

© 2007 Pearson Education, Inc. All rights reserved.

46 of 93

46

Outline

fig06_11.c

(4 of 4 )

© 2007 Pearson Education, Inc. All rights reserved.

47 of 93

Common Programming Error 6.8

Assuming that elements of a local static�array are initialized to zero every time the function in which the array is defined is called.

47

© 2007 Pearson Education, Inc. All rights reserved.

48 of 93

6.5 Passing Arrays to Functions

  • Passing arrays
    • To pass an array argument to a function, specify the name of the array without any brackets

int myArray[ 24 ];

myFunction( myArray, 24 );

      • Array size usually passed to function
    • Arrays passed call-by-reference
    • Name of array is address of first element
    • Function knows where the array is stored
      • Modifies original memory locations
  • Passing array elements
    • Passed by call-by-value
    • Pass subscripted name (i.e., myArray[ 3 ]) to function

48

© 2007 Pearson Education, Inc. All rights reserved.

49 of 93

6.5 Passing Arrays to Functions

  • Function prototype

void modifyArray( int b[], int arraySize );

    • Parameter names optional in prototype
      • int b[] could be written int []
      • int arraySize could be simply int

49

© 2007 Pearson Education, Inc. All rights reserved.

50 of 93

Performance Tip 6.3

Passing arrays by reference makes sense for performance reasons. If arrays were passed by value, a copy of each element would be passed. For large, frequently passed arrays, this would be time consuming and would consume considerable storage for the copies of the arrays.

50

© 2007 Pearson Education, Inc. All rights reserved.

51 of 93

51

Outline

fig06_12.c

© 2007 Pearson Education, Inc. All rights reserved.

52 of 93

Software Engineering Observation 6.2

It is possible to pass an array by value (by�using a simple trick we explain in Chapter 10).

52

© 2007 Pearson Education, Inc. All rights reserved.

53 of 93

53

Outline

fig06_13.c

(1 of 3 )

Function prototype indicates function will take an array

Array a is passed to modifyArray by passing only its name

© 2007 Pearson Education, Inc. All rights reserved.

54 of 93

54

Outline

fig06_13.c

(2 of 3 )

Array element is passed to modifyElement by passing a[ 3 ]

© 2007 Pearson Education, Inc. All rights reserved.

55 of 93

55

Outline

fig06_13.c

(3 of 3 )

© 2007 Pearson Education, Inc. All rights reserved.

56 of 93

56

Outline

fig06_14.c

(1 of 2 )

const qualifier tells compiler that array cannot be changed

Any attempts to modify the array will result in errors

© 2007 Pearson Education, Inc. All rights reserved.

57 of 93

57

Outline

fig06_14.c

(2 of 2 )

© 2007 Pearson Education, Inc. All rights reserved.

58 of 93

Software Engineering Observation 6.3

The const type qualifier can be applied to an array parameter in a function definition to prevent the original array from being modified in the function body. This is another example of the principle of least privilege. Functions should not be given the capability to modify an array unless it is absolutely necessary.

58

© 2007 Pearson Education, Inc. All rights reserved.

59 of 93

6.6 Sorting Arrays

  • Sorting data
    • Important computing application
    • Virtually every organization must sort some data
  • Bubble sort (sinking sort)
    • Several passes through the array
    • Successive pairs of elements are compared
      • If increasing order (or identical ), no change
      • If decreasing order, elements exchanged
    • Repeat
  • Example:
    • original: 3 4 2 6 7
    • pass 1: 3 2 4 6 7
    • pass 2: 2 3 4 6 7
    • Small elements "bubble" to the top

59

© 2007 Pearson Education, Inc. All rights reserved.

60 of 93

Performance Tip 6.4

Often, the simplest algorithms perform poorly. Their virtue is that they are easy to write, test and debug. However, more complex algorithms are often needed to realize maximum performance.

60

© 2007 Pearson Education, Inc. All rights reserved.

61 of 93

61

Outline

fig06_15.c

(1 of 2 )

© 2007 Pearson Education, Inc. All rights reserved.

62 of 93

62

Outline

fig06_15.c

(2 of 2 )

If any two array elements are out of order, the function swaps them

© 2007 Pearson Education, Inc. All rights reserved.

63 of 93

6.7 Case Study: Computing Mean, Median and Mode Using Arrays

  • Mean – average
  • Median – number in middle of sorted list
    • 1, 2, 3, 4, 5
    • 3 is the median
  • Mode – number that occurs most often
    • 1, 1, 1, 2, 3, 3, 4, 5
    • 1 is the mode

63

© 2007 Pearson Education, Inc. All rights reserved.

64 of 93

64

Outline

fig06_16.c

(1 of 6 )

© 2007 Pearson Education, Inc. All rights reserved.

65 of 93

65

Outline

fig06_16.c

(2 of 6 )

© 2007 Pearson Education, Inc. All rights reserved.

66 of 93

66

Outline

fig06_16.c

(3 of 6 )

Once the array is sorted, the median will be the value of the middle element

© 2007 Pearson Education, Inc. All rights reserved.

67 of 93

67

Outline

fig06_16.c

(4 of 6 )

© 2007 Pearson Education, Inc. All rights reserved.

68 of 93

68

Outline

fig06_16.c

(5 of 6 )

© 2007 Pearson Education, Inc. All rights reserved.

69 of 93

69

Outline

fig06_16.c

(6 of 6 )

© 2007 Pearson Education, Inc. All rights reserved.

70 of 93

70

Outline

(1 of 2 )

© 2007 Pearson Education, Inc. All rights reserved.

71 of 93

71

Outline

(2 of 2 )

© 2007 Pearson Education, Inc. All rights reserved.

72 of 93

6.8 Searching Arrays

  • Search an array for a key value
  • Linear search
    • Simple
    • Compare each element of array with key value
    • Useful for small and unsorted arrays

72

© 2007 Pearson Education, Inc. All rights reserved.

73 of 93

73

Outline

fig06_18.c

(1 of 3 )

© 2007 Pearson Education, Inc. All rights reserved.

74 of 93

74

Outline

fig06_18.c

(2 of 3 )

© 2007 Pearson Education, Inc. All rights reserved.

75 of 93

75

Outline

fig06_18.c

(3 of 3 )

Linear search algorithm searches through every element in the array until a match is found

© 2007 Pearson Education, Inc. All rights reserved.

76 of 93

6.8 Searching Arrays

  • Binary search
    • For sorted arrays only
    • Compares middle element with key
      • If equal, match found
      • If key < middle, looks in first half of array
      • If key > middle, looks in last half
      • Repeat
    • Very fast; at most n steps, where 2n > number of elements
      • 30 element array takes at most 5 steps

25 > 30 so at most 5 steps

76

© 2007 Pearson Education, Inc. All rights reserved.

77 of 93

77

Outline

fig06_19.c

(1 of 6 )

© 2007 Pearson Education, Inc. All rights reserved.

78 of 93

78

Outline

fig06_19.c

(2 of 6 )

© 2007 Pearson Education, Inc. All rights reserved.

79 of 93

79

Outline

fig06_19.c

(3 of 6 )

If value is found, return its index

If value is too high, search the left half of array

If value is too low, search the right half of array

© 2007 Pearson Education, Inc. All rights reserved.

80 of 93

80

Outline

fig06_19.c

(4 of 6 )

© 2007 Pearson Education, Inc. All rights reserved.

81 of 93

81

Outline

fig06_19.c

(5 of 6 )

© 2007 Pearson Education, Inc. All rights reserved.

82 of 93

82

Outline

fig06_19.c

(6 of 6 )

© 2007 Pearson Education, Inc. All rights reserved.

83 of 93

6.9 Multiple-Subscripted Arrays

  • Multiple subscripted arrays
    • Tables with rows and columns (m by n array)
    • Like matrices: specify row, then column
  • Initialization
    • int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
    • Initializers grouped by row in braces
    • If not enough, unspecified elements set to zero

int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };

  • Referencing elements
    • Specify row, then column

printf( "%d", b[ 0 ][ 1 ] );

83

© 2007 Pearson Education, Inc. All rights reserved.

84 of 93

Common Programming Error 6.9

Referencing a double-subscripted array element as a[ x, y ] instead of a[ x ][ y ]. C interprets a[ x, y ] as a[ y ], and as such it does not cause a syntax error.

84

© 2007 Pearson Education, Inc. All rights reserved.

85 of 93

Fig. 6.20 | Double-subscripted array with three rows and four columns.

85

© 2007 Pearson Education, Inc. All rights reserved.

86 of 93

86

Outline

fig06_21.c

(1 of 2 )

array1 is initialized with both rows full

array2 and array3 are initialized only partially

© 2007 Pearson Education, Inc. All rights reserved.

87 of 93

87

Outline

fig06_21.c

(2 of 2 )

© 2007 Pearson Education, Inc. All rights reserved.

88 of 93

88

Outline

fig06_22.c

(1 of 6 )

Each row in the array corresponds to a single student’s set of grades

© 2007 Pearson Education, Inc. All rights reserved.

89 of 93

89

Outline

fig06_22.c

(2 of 6 )

average function is passed a row of the array

© 2007 Pearson Education, Inc. All rights reserved.

90 of 93

90

Outline

fig06_22.c

(3 of 6 )

© 2007 Pearson Education, Inc. All rights reserved.

91 of 93

91

Outline

fig06_22.c

(4 of 6 )

© 2007 Pearson Education, Inc. All rights reserved.

92 of 93

92

Outline

fig06_22.c

(5 of 6 )

© 2007 Pearson Education, Inc. All rights reserved.

93 of 93

93

Outline

fig06_22.c

(6 of 6 )

© 2007 Pearson Education, Inc. All rights reserved.