a first book of ansi c fourth edition

101
A First Book of ANSI C Fourth Edition Chapter 8 Arrays

Upload: katen

Post on 07-Jan-2016

39 views

Category:

Documents


2 download

DESCRIPTION

A First Book of ANSI C Fourth Edition. Chapter 8 Arrays. Objectives. One-Dimensional Arrays Array Initialization Arrays as Function Arguments Case Study: Computing Averages and Standard Deviations Two-Dimensional Arrays Common Programming and Compiler Errors. Chapter 8 Arrays. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: A First Book of ANSI C Fourth Edition

A First Book of ANSI CFourth Edition

Chapter 8Arrays

Page 2: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 2

Objectives

• One-Dimensional Arrays

• Array Initialization

• Arrays as Function Arguments

• Case Study: Computing Averages and Standard Deviations

• Two-Dimensional Arrays

• Common Programming and Compiler Errors

Page 3: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 3

Chapter 8 Arrays

• The variables used so far have all had a common characteristic : each variable can only be used to store a single value at a time .

• These types of variables are called scalar variables .

Page 4: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 4

• A scalar variable is a single variable whose stored value is an atomic type .

• This means that the value cannot be further subdivided or separated into a legitimate data type

• Frequently we may have a set of values , all of the same data type , that form a logical group .

Page 5: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 5

• A simple list consisting of individual items of the same scalar data type is called a single-dimensional array .

• In this chapter we describe how single-dimensional arrays are declared , initialized , stored inside a computer , and used .

• We will explore the use of single-dimensional arrays with example programs and present the procedures for declaring and using multidimensional arrays .

Page 6: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 6

8.1 One Dimensional Arrays

• A single-dimensional array , which is also referred to as a one-dimensional array , is a list of values of the same data type .

• To declare that grades is to be used to store five individual integer values requires the declaration statement

int grades[5] ;

Page 7: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 7

• Further examples of array declarations are

• char code[4] ; /* an array of four character codes */

• double prices[6] ;/* an array of six double precision prices */

• float amount [100] ;/*an array of 100 floating point amounts */

Page 8: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 8

• Each array has sufficient memory reserved for it to hold the number of data items given in the declaration statement .

• Thus , the array named code has storage reserved for four characters ,the prices array has storage reserved for six double precision numbers , and the array named amount has storage reserved for 100 floating point numbers .

Page 9: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 9

• Each item in a list is officially called an element or component of the array .

• Because each item in the list is stored sequentially , any single item can be accessed by giving the name of the array and the position of the item in the array .

Page 10: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 10

• The element’s position is called its subscript or index value .

• The first element has a subscript of 0 , the second element has subscript of 1 , and so on .

• The subscript gives the number of elements to move over , starting from the beginning of the array , to locate the desired element .

• In C , the array name and subscript are combined by listing the subscript in square brackets after the array name .

Page 11: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 11

Introduction (continued)

Page 12: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 12

• Subscripted variables can be used anywhere that scalar variables are valid .

• Examples using the elements of the grades array are

• grades [0] = 98 ;• grades [1] = grades [0] – 11 • grades [2] = 2 * ( grades [0] – 6 );• grades [3] = 79 ;• grades [4] = (grades [2] + grades [3] – 3 ) / 2 ;• total = grades [0] + grades [1] + grades [2] +

grades [3] + grades [4] ;

Page 13: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 13

• The subscript contained within square brackets need not be an integer .

• Any expression that evaluates to an integer may be used as a subscript .

• For example , assuming that i and j are integer variables , the following subscripted variables are valid :

• grades [i] • grades [2*i] • grades [j-i]

Page 14: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 14

• One extremely important advantage of using integer expressions as subscripts is that it allows sequencing through an array using a for loop .

• This makes statements such as

total = grades[1]+ grades[2]+ grades[3]+ grades[4]+ grades[5] ;

unnecessary .

Page 15: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 15

• The subscript value in each of the subscripted variables in this statement can be replaced by the counter in a for loop to access each element in the array sequentially .

• For example , the code

• total = 0 ; /* initialize total to zero */• for (i = 0 ; i <= 4 ; ++i )• total = total + grades [i] ;/* add in a grade */

• sequentially retrieves each array element and adds the element to the total .

Page 16: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 16

• Here the variable i is used both as the counter in the for loop and as a subscript .

• As i increases by one each time through the for loop , the next element in the array is referenced .

• The procedure for adding the array elements within the for loop is the same procedure we have used many times before .

Page 17: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 17

• When an element with a higher value is located , that element becomes the new maximum .

• maximum = price[0] ;

• for (i = 1 ; i <= 999 ; ++i)

• if (price[i] > maximum)

• maximum = price[i] ;

Page 18: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 18

Input and Output of Array Values

• Individual array elements can be assigned values using individual assignment statements or , interactively , using the scanf( ) function .

Page 19: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 19

• Examples of individual data entry statements are

• price[5] = 10.69 ;

• scanf (“%d %lf”, &grades[0] , &price[2] )

• scanf (“%c”, &code[0] );

• scanf (“%d %d %d”, &grades[0], &grades[1], &grades[2]);

Page 20: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 20

• Alternatively , a for statement can be used to cycle through the array for interactive data input .

• For example , the code • for (i = 0 ; i <= 4 ; ++i )• {• printf (“Enter a grade : ”);• scanf (“%d”, &grade[i] );• }• prompts the user for five grades . • The first grade entered is stored in grades[0] , the

second in grades[1] , and so on until all five grades are entered .

Page 21: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 21

• One caution should be mentioned about storing data in an array .

• C does not check the value of the index being used .

• If an array has been declared as consisting of 10 elements , for example , and you use an index of 12 , which is outside the bounds of the array , C will not notify you of the error when the program is compiled .

Page 22: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 22

• During output , individual array elements can be displayed using the printf( ) function or complete sections of the array can be displayed by including a printf( ) function call within a for loop .

• Examples of this are

• printf (“%lf ,” price[6] );

• printf (“The value of element %d is %d”, i , grades[i] );

• for ( n = 5 ; n <= 20 ; ++n )

• printf (“%d %lf”, n , price[n] );

Page 23: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 23

• The first call to printf( ) displays the value of the double precision subscripted variable price[6] .

• The second call to printf( ) displays the value of i and the value of grades[i] .

• Before this statement can be executed , i needs to have an assigned value .

• Finally , the last example includes printf( ) within a for loop .

• Both the value of the index and the value of the elements from 5 to 20 are displayed .

Page 24: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 24

• Program 8.1 illustrates these input and output techniques using an array named grades that is defined to store five integer numbers .

• Included in the program are two for loops .

• The first for loop is used to cycle through each array element and allows the user to input individual array values .

• After five values have been entered , the second for loop is used to display the stored values .

Page 25: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 25

• Program 8.1

• #include <stdio.h>• int main ( )• {• int i , grades[5] ;• for (i = 0 ; i <= 4 ; ++i) /* Enter five grades */• {• printf (“Enter a grade :”) ;• scanf (“%d”, &grades[i] ) ;• }• for ( i = 0 ; i <= 4 ; ++i ) /* Print five grades */• printf (“\ngrades %d is %d” , i , grades[i] );• return 0 ;• }

Page 26: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 26

• In reviewing the output produced by Program 8.1 , pay particular attention to the difference between the subscript value displayed and the numerical value stored in the corresponding array element .

• The subscript value refers to the location of the element in the array , whereas the subscripted variable refers to the value stored in the designed location .

Page 27: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 27

Sample output:Enter a grade: 85Enter a grade: 90Enter a grade: 78Enter a grade: 75Enter a grade: 92grades 0 is 85grades 1 is 90grades 2 is 78grades 3 is 75grades 4 is 92

Input and Output of Array Values (continued)

Page 28: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 28

• Program 8.2

• #include <stdio.h>• int main( )• {• int i , grades[5] , total = 0 ;• for (i = 0 ; i <= 4 ; ++i ) /* Enter five grades */• {• printf (“Enter a grade : ”) ;• scanf (“%d”, &grades[i] ) ;• }

Page 29: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 29

• printf (“\nThe total of the grades ”) ;• for (i = 0 ; i <= 4 ; ++i) /* Display and total the

grades */• {• printf (“%d ”, grades[i] );• total += grades[i] ;• }• printf (“ is %d ”, total );• return 0 ;• }

Page 30: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 30

• Following is a sample run using Program 7. 2 :

• Enter a grade : 85

• Enter a grade : 90

• Enter a grade : 78

• Enter a grade : 75

• Enter a grade : 92

• The total of the grades 85 90 78 75 92 is 420

Page 31: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 31

• Notice that in Program 8.2 , unlike Program 8.1 , only the numerical value stored in each array element is displayed and not their subscript values .

• Although the second for loop was used to accumulate the total of each element , the accumulation could also have been accomplished in the first loop by placing the statement total += grades[i] ; after the scanf( ) call used to enter a value ..

Page 32: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 32

• Also notice that the printf( ) call used to display the total made outside of the second for loop so that the total is displayed only once , after all values have been added to the total .

• If this printf( ) call is placed inside the for loop five totals are displayed , with only the last displayed total containing the sun of all of the array values

Page 33: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 33

Statement is outside of the second for loop; total is displayed only once, after all values have been added

Input and Output of Array Values (continued)

Page 34: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 34

8.2 Array Initialization

• Arrays , like scalar variables , can be declared either inside or outside a function .

• Arrays declared inside a function are local arrays , and arrays declared outside a function are global arrays .

Page 35: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 35

Array Initialization (continued)

1 #define SIZE1 202 #define SIZE2 253 #define SIZE3 1545 int gallons[SIZE1]; /* a global array */6 static int dist[SIZE2]; /* a static global array */78 int main()9 {10 int miles[SIZE3]; /* an auto local array */11 static int course[SIZE3]; /* static local array */12 .13 .14 return 0;15 }

Page 36: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 36

• For example , consider the following section of code :

• int gallons[20] ; /* a global array */• static double dist[25] ; /* a static global array */• void mpg (int) ; /* function prototype */• int main ( )• {• int i ;• for ( i = 1 ; i <= 10 ; ++i )• mpg (i) ;

…• return 0 ;• }

Page 37: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 37

• void mpg (int carNum)

• {

• int miles[15] ; /* an automatic local array */

• static double course[15] ; /* a static local array */

• return ;

• }

Page 38: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 38

• As indicated in the code , both the dist and gallons arrays are globally declared arrays , miles is an automatic local array , and course is a static local array .

• As with scalar variables , all global arrays and local static arrays are created once , at compilation time , and retain their values until main( ) finishes executing .

• auto arrays are created and destroyed each time the function they are local to is called .

• Thus , the dist , gallons , and course arrays are created once , and the miles array is created and destroyed ten times .

Page 39: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 39

• Array elements can be initialized within their declaration statements in the same manner as scalar variables , except that the initializing elements must be included in braces .

• Examples of such initializations for automatic , static , and global arrays are

• int grades[5] = { 98, 87, 92, 79, 85 };• char codes[6] = { ‘s’,‘a’,‘m’,‘p’,‘l’,‘e’};• double width[7] = { 10.96, 6.43, 2.58, .86, 5.89,

7.56, 8.22} ;• static int temp[4] = {10 , 20 , 30 , 40 } ;• static float temp[4] = { 98.6, 97.2, 99.0, 101.5} ;

Page 40: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 40

• Initializers are applied in the order they are written , with the first value used to initialize element 0 , the second value used to initialize element 1 , and so on , until all values have been used .

Page 41: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 41

• Because white space is ignored in C , initializations may be continued across multiple lines .

• For example , the declaration • int gallons[20]={19,16,14,19,20,18, /* initializing • values */• 12,10,22,15,18,17, /* may extend across */• 16,14,23,19,15,18, /* multiple lines */ 21,5 }• uses four lines to initialize all of the array elements

.

Page 42: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 42

• If the number of initializers is less than the declared number of elements listed in square brackets the initializers are applied starting with array element 0 .

• 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 .

Page 43: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 43

• Unfortunately , there is no method to either indicate repetition of an initialization value or initialize later array elements without first specifying values for earlier elements .

• If no specific initializers are given in the declaration statement , all numerical array elements are set to zero .

Page 44: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 44

• 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, 11 } ;• reserves enough storage room for five

elements . • Similarly , the following two declarations are

equivalent :• char codes[6] = { ‘s’,‘a’,‘m’,‘p’,‘l’,‘e’};• char codes[ ] = { ‘s’,‘a’,‘m’,‘p’,‘l’,‘e’}

Page 45: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 45

• Both of these declarations set aside six character locations for an array named codes .

• An interesting and useful simplification can also be used when initializing character arrays .

• For example , the declaration

• char codes[ ] = “sample”; /* no braces or commas */

• uses the string “sample” to initialize the codes array .

Page 46: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 46

• Recall that a string is any sequence of characters enclosed in double quotes .

• This last declaration creates an array named codes having seven elements and fills the array with the seven characters illustrated in Figure 8.6 .

• The first six characters , as expected , consist of the letters s, a, m, p, l, and e.

• The last character , which is the escape sequence \0 , is called the null character .

Page 47: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 47

codes[0]

codes[1]

codes[2]

codes[3]

codes[4]

codes[5]

codes[6]

s a m p l e \0

• The null character is automatically appended to all strings by the C compiler .

Page 48: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 48

Array Initialization (continued)

Page 49: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 49

Array Initialization (continued)

Page 50: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 50

8.3 Arrays as Function Arguments

• Individual array elements are passed to a function by simply including them as subscripted variables in the function call argument list .

• For example , the function call

findMin (grades[2] , grades[6] ) ;

passes the values of the elements grades[2] and grades[6] to the function findMin ( ) .

Page 51: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 51

• Passing a complete array to a function is in many respects an easier operation than passing individual elements .

• The called function receives access to the actual array , rather than a copy of the values in the array .

• For example , if grades is an array , the function call findMax (grades) ; makes the complete grades array available to the findMax ( ) function .

• This is different from passing a single variable to a function .

Page 52: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 52

• Recall that when a single scalar argument is passed to a function , the called function receives only a copy of the passed value , which is stored in one of the function’s value parameters .

• If arrays were passed in this manner , a copy of the complete array would have to be created .

• For large arrays , making duplicate copies of the array for each function call would waste computer storage , consume execution time , and frustrate the effort to return multiple element changes made by the called program .

Page 53: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 53

• To avoid these problems , the called function is given direct access to the original array .

• Thus , any changes made by the called function are made directly to the array itself .

• For the following specific examples of function calls , assume that the arrays nums , keys , units , and prices are declared as :

• int nums[5] ; • char keys[256] ; • double units[500],prices[500] ;

Page 54: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 54

• For these arrays , the following function calls can be made :

• findMax(nums) ;• findCh(keys) ;• calcTot(nums , units , prices) ;

• In each case , the called function receives direct access to the named array .

Page 55: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 55

• On the receiving side , the called function must be alerted that an array is being made available .

• For example , suitable function headers for the previous functions are

• int findMax (int vals[5]) • char findCh (chr inKeys[256])• void calcTot (int arrl[5] , double arr2[500] ,

double arr3[500])

Page 56: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 56

• In each of these function declarations , the names in the parameter list are chosen by the programmer and are local to the function .

• However , the internal local names used by the functions still refer to the original array created outside the function .

• This is made clear in Program 8.4 .

Page 57: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 57

• Program 8.4

• #include <stdio.h>

• void findMax (int [5]) ; /* function prototype */

• int main( )

• {

• int nums[5] = { 2, 18, 1, 27, 16} ;

• findMax (nums) ;

• return 0 ;

• }

Page 58: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 58

• void findMax(int vals[5]) /* find the maximum value */

• {

• int i , max = vals[0] ;

• for ( i = 1 ; i <= 4 ; ++i )

• if (max < vals[i])

• max = vals[i] ;

• printf (“The maximum value is %d”, max );

• return ;

• }

Page 59: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 59

Size can be omitted

Arrays as Function Arguments (continued)

Page 60: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 60

• Since only one item is passed to findMax , the number of elements in the array need not be included in the declaration for vals .

• In fact , it is generally advisable to omit the size of the array in the function header line .

• For example , consider the more general form of findMax ( ) , which can be used to find the maximum value of an integer array of arbitrary size .

Page 61: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 61

• int findMax(int vals[ ] , int numEls ) /* find the maximum value */

• {

• int i , max = vals[0] ;

• for ( i = 1 ; i < numEls ; ++i )

• if (max < vals[i])

• max = vals[i] ;

• return(max) ;

• }

Page 62: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 62

• The more general form of findMax( ) declares that the function returns an integer value .

• The function expects the starting address of an integer array and the number of elements in the array as arguments .

• Then , using the number of elements as the boundary for its search , the function’s for loop causes each array element to be examined in sequential order to locate the maximum value .

• Program 8.5 illustrates the use of findMax( ) in a complete program .

Page 63: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 63

• Program 8.5 • #include <stdio.h>• int findMax(int [ ] , int); /* function prototype */• int main( )• {• int nums[5] = { 2, 18, 1, 27, 16} ;• • printf (“The maximum value is %d”,

findMax(nums ,5)) ;• return 0 ;• }

Page 64: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 64

• int findMax(int vals[ ], int numEls)

• {

• int i , max = vals[0] ;

• for (i = 1 ; i < numEls ; ++i)

• if (max < vals[i])

• max = vals[i] ;

• return(max) ;

• }

• The output displayed when Program 8. 5 is executed is

• The maximum value is 27

Page 65: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 65

Arrays as Function Arguments (continued)

Page 66: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 66

Case Study: Computing Averages and Standard Deviations

• Two statistical functions are created to determine the average and standard deviation, respectively, of an array of numbers

Page 67: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 67

Write the Functions

Page 68: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 68

Write the Functions (continued)

Page 69: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 69

8.5 Two-Dimensional Arrays• A two-Dimensional array , which is sometimes

referred to as a table , consists of both rows and columns of elements .

• For example , the array of numbers

• is a two-dimensional array of integers .

8 16 9 52

3 15 27 6

14 25 2 10

Page 70: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 70

• 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 .

Page 71: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 71

• Calling the array val , the appropriate declaration for this two-dimensional array is

int val[3] [4] ;• Similarly , the declarations double prices[10] [5] ; char code[6] [26] ;• declare that the array prices consists of 10 rows

and 5 columns of double precision numbers and that the array code consists of 6 rows and 26 columns of characters .

Page 72: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 72

• Each element in a two-dimensional array is located by identifying its position in the array .

• As illustrated in Figure 8.9 , the term val[1] [3] uniquely identifies the element in row 1 , column 3 .

• As with single-dimensional array variables , double-dimensional array variables can be used anywhere that scalar variables are valid .

Page 73: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 73

Two-Dimensional Arrays (continued)

Page 74: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 74

• As with single-dimensional arrays , double-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 .

Page 75: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 75

• For example , the declaration • int val[3][4] = { { 8, 16, 9, 52 } ,• { 3, 15, 27, 6 } ,• { 14, 25, 2, 10 } } ;• 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 .

Page 76: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 76

• 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 } ;

Page 77: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 77

• As with single-dimensional arrays , double-dimensional arrays may be displayed by individual element notation or by using loops .

• This is illustrated by Program 8.7 , which displays all the elements of a three-by-four two-dimensional array using two different techniques .

Page 78: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 78

• Program 8.7

• #include<stdio.h>• int main( )• {• int i , j , val[3][4] = { 8 , 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][0] , 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] ,val[2][3]) ;

Page 79: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 79

• printf(“\nDisplay of val array using a nested for loop”) ;

• for ( i = 0 ; i < 3 ; ++i )• {• printf(“\n”) ; /* start a new line for each

row */• for (j = 0 ; j < 4 ; ++j ) • printf(“%2d ” , val[i][j]) ;• }• return 0 ;• }

Page 80: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 80

• The display produced by Program 8.7 is

• Display of val array by explicit element

• 8 16 9 52

• 3 15 27 6

• 14 25 2 10

• Display of val array using a nested for loop

• 8 16 9 52

• 3 15 27 6

• 14 25 2 10

Page 81: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 81

Two-Dimensional Arrays (continued)

Page 82: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 82

• The first display of the val array produced by Program 8.7 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 .

Page 83: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 83

• In Program 8.7 , 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 row 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 .

Page 84: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 84

• 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 in Program 8.8 is used to multiply each element in the val array by the scalar number 10 and display the resulting value .

Page 85: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 85

• Program 8.8

• #include <stdio.h>

• int 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 (“\nDisplay of multiplied elements\n”) ;

Page 86: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 86

• for ( i = 0 ; i < 3 ; ++i )• {• printf(“\n”) ; /* start a new line */• for ( j = 0 ; j < 4 ; ++j )• {• val[i][j] = val[i][j] * 10 ;• printf (“%3d ” , val[i][j] ) ;• } /* end of inner loop */• } /* end of outer loop */• return 0 ;• }

Page 87: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 87

Two-Dimensional Arrays (continued)

Page 88: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 88

• Passing two-dimensional arrays into functions is a process identical to passing one-dimensional arrays .

• The called function receives access to the entire array .

• For example , the function call display(val) ; makes the complete val array available to the function named display( ) .

• Thus , any changes made by display( ) are made directly to the val array .

Page 89: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 89

• If the array is a global one , there is no need to pass the array because the function could access the array by its global name .

• Program 8.9 illustrates passing a local , two-dimensional array into a function that displays the array’s values .

Page 90: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 90

• Program 8.9

• #include<stdio.h>• void display(int [3][4]) ; /* function prototype */• int main( )• {• int val[3][4] = { 8 ,16 ,9 ,52 ,• 3 ,15 ,27 ,6 ,• 14 ,25 ,2 ,10} ;• display(val) ;• return 0 ;• }

Page 91: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 91

• void display(int nums[3][4])• {• int rowNum , colNum ;• for (rowNum = 0 ; rowNum < 3 ; ++rowNum)• {• for(colNum = 0 ; rowNum < 4 ; ++rowNum)• printf(“%4d”, nums[rowNum][colNum]) ;• printf(“\n”) ;• }• return ;• }

Page 92: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 92

• Only one array is created in Program 8.9 . • This array is known as val in main( ) and as nums

in display ( ) . • Thus , val[0][2] refers to the same element as

nums[0][2] . • Notice the use of the nested for loop in Program

8.9 . • Nested for statements are especially useful when

dealing with multidimensional arrays because they allow the programmer to cycle through each element .

Page 93: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 93

• In Program 8.9 , the variable rowNum controls the outer loop and the variable colNum controls the inner loop .

• For each pass through the outer loop , which corresponds to a row , the inner loop makes one pass through the column elements .

• After a complete row is printed , the \n escape sequence causes a new line to be started for the next row .

Page 94: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 94

• The effect is a display of the array in a row-by-row fashion :

• 8 16 9 52

• 3 15 27 6

• 14 25 2 10

Page 95: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 95

Row size can be omitted

Two-Dimensional Arrays (continued)

Page 96: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 96

Internal Array Element Location Algorithm (continued)

Page 97: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 97

Larger Dimensional Arrays

• A three-dimensional array can be viewed as a book of data tables (the third subscript is called the rank)– int response[4][10][6];

• 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

• 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

• Arrays of three, four, five, six, or more dimensions can be viewed as mathematical n- tuples

Page 98: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 98

Common Programming Errors

• Forgetting to declare the array

• Using a subscript that references a nonexistent array element

• Not using a large enough conditional value in a for loop counter to cycle through all the array elements

• Forgetting to initialize the array

Page 99: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 99

Common Compiler Errors

Page 100: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 100

Summary

• A single-dimensional array is a data structure that can store a list of values of the same data type

• Elements are stored in contiguous locations– Referenced using the array name and a subscript

• Single-dimensional arrays may be initialized when they are declared

• Single-dimensional arrays are passed to a function by passing the name of the array as an argument

Page 101: A First Book of ANSI C Fourth Edition

A First Book of ANSI C, Fourth Edition 101

Summary (continued)

• A two-dimensional array is declared by listing both a row and a column size with the data type and name of the array

• Two-dimensional arrays may be initialized when they are declared

• Two-dimensional arrays are passed to a function by passing the name of the array as an argument