0% found this document useful (0 votes)
6 views

Lecture 07-1

Uploaded by

rantan51244
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Lecture 07-1

Uploaded by

rantan51244
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 115

1

7
C Arrays
2

課程目標
在本章中,你將會學到:
▪ 使用陣列資料結構表示串列及表格中的數值。
▪ 宣告陣列、初始化陣列,以及存取陣列中的個
別元素。
▪ 定義符號常數。
▪ 將陣列傳遞給函式。
▪ 使用陣列進行儲存、排序和搜尋串列以及表單
中的數值。
▪ 定義和操作多維陣列。
3

6.1 簡介
6.2 陣列
6.3 定義陣列
6.4 使用陣列的例子
6.5 傳遞陣列給函式
6.6 陣列的排序
6.7 範例研究:使用陣列來計算平均數、中位數以及眾數
6.8 搜尋陣列
6.9 多維陣列
4

C Program Design
C Arrays
▪Basics
5

6.2 Array
▪ 陣列
– 一組連續的記憶體位置
– 相同名稱以及相同型別
▪ 為了引用陣列中的某個元素,我們要指定
– 陣列的名稱
– 位置編號
▪ 格式:
arrayname[ position number ]
– 第一個元素在位置 0
– 具有n個元素的陣列,陣列名稱為c:
- c[ 0 ], c[ 1 ]...c[ n – 1 ]
6

Arrays
score
Array is a data structure that
stores contiguous data elements

bytes bytes
50 200
記 of the same type.
address
distance 憶
Examples:

int score[50];
bytes
400

char address[50];
double distance[50];
7

Examples:
Arrays
int score[50];
char address[50];
double distance[50];

score
score[0]

address score[1]
distance
..
.

score[49]
8

Examples:
Arrays
int score[50];
char address[50];
double distance[50];

score

address[0]
address[1]
address address[2]

distance ..
.
address[49]
9

Examples:
Arrays
int score[50];
char address[50];
double distance[50];

score

distance[0]

address
distance ..
.

distance[49]
10

Examples:
Array
int score[50];
char address[50];
double distance[50];

▪ Array elements are like normal variables


score[ 0 ] = 90;
printf( "%d", score[ 0 ] );

▪ Perform operations in subscript.


– If x equals 3
c[ 5 - 2 ]  c[ 3 ]  c[ x ]
11

Array 使用注意事項
▪ Array 之索引(index)由0開始
– 一陣列若含n元素,其索引由0至n-1

▪ C Compiler對陣列索引不做out of range檢查
– 易產生程式錯誤,甚或系統失敗
– 寫程式時程式設計師應保證陣列索引不超出範圍
12

6.2 陣列
▪ 陣列元素如同一般的變數
c[ 0 ] = 3;
printf( "%d", c[ 0 ] );
– 在下標中執行運算,假如x=3
c[ 5 - 2 ] == c[ 3 ] == c[ x ]
13

圖6.2 |運算子的優先順序
14

C Program Design
C Arrays
▪Defining Arrays
15

6.3 Defining Arrays


▪ 當定義陣列時,需指定
– 名稱
– 陣列型別
– 元素個數
arrayType arrayName[ numberOfElements ];
– 範例:
int c[ 10 ];
float myArray[ 3284 ];

▪ 定義多個同樣型別的陣列
– 格式類似一般的變數
– 範例:
int b[ 100 ], x[ 27 ];
16

Defining Arrays

arrayType arrayName[numberOfElements];

Examples:

int c[10];
float myArray[3284];
17

Defining Multiple Arrays of Same Type

arrayType arrayName[numberOfElements];

Examples:

int age[10], score[50];


double distance[50], average[100];
18

C Program Design
C Arrays
▪Array Initialization
19

6.4 使用陣列的例子
▪ 初始值
int n[ 5 ] = { 1, 2, 3, 4, 5 };
– 如果初始值的個數不足,右方的元素將變為零
int n[ 5 ] = { 0 }
- 所有的元素皆為 0
– 假如初始值太多,就會產生語法錯誤
– C並不會進行陣列範圍檢查
▪ 假如省略陣列的大小,會以初始值來決定
int n[ ] = { 1, 2, 3, 4, 5 };
– 5 個初始值,因此這是一個具有5個元素的陣列
20

Initializers

int n1[10]={1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

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

int n3[10]={0};

int n4[10];

int n5[]={1, 2, 3, 4, 5, 6, 7, 8, 9, 10};


21

Example:Initializers Debug Mode

#include <stdio.h>

main()
{
int n1[10]={1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // all elements are initialized
int n2[10]={1, 2, 3, 4, 5}; // rightmost elements become 0
int n3[10]={0}; // rightmost elements become 0
int n4[10]; // defined an array of size 10; don’t guess their values
int n5[]={1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // initializer detetermines the size
int i;

for(i = 0; i<10; i++)


printf("n1[%d]=%2d n2[%d]=%2d n3[%d]=%2d n4[%d]=%2d n5[%d]=%2d\n",
i, n1[i], i, n2[i], i, n3[i], i, n4[i], i, n5[i]);
}
22

Example:Initializers Release Mode

#include <stdio.h>

main()
{
int n1[10]={1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // all elements are initialized
int n2[10]={1, 2, 3, 4, 5}; // rightmost elements become 0
int n3[10]={0}; // rightmost elements become 0
int n4[10]; // defined an array of size 10; don’t guess their values
int n5[]={1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // initializer detetermines the size
int i;

for(i = 0; i<10; i++)


printf("n1[%d]=%2d n2[%d]=%2d n3[%d]=%2d n4[%d]=%2d n5[%d]=%2d\n",
i, n1[i], i, n2[i], i, n3[i], i, n4[i], i, n5[i]);
}
1 /* Fig. 6.3: fig06_03.c 23
2 initializing an array */
3 #include <stdio.h>
Outline
4
5 /* function main begins program execution */
6 int main( void )
fig06_03.c
7 {
8 int n[ 10 ]; /* n is an array of 10 integers */
9 int i; /* counter */
(1 of 2 )
10
11 /* initialize elements of array n to 0 */
12 for ( i = 0; i < 10; i++ ) { for迴圈會分別將陣列的每個元
13 n[ i ] = 0; /* set element at location i to 0 */ 素初始化
14 } /* end for */
15
16 printf( "%s%13s\n", "Element", "Value" );
17
18 /* output contents of array n in tabular format */
19 for ( i = 0; i < 10; i++ ) { for迴圈會輸出所有的陣列元素
20 printf( "%7d%13d\n", i, n[ i ] );
21 } /* end for */
22
23 return 0; /* indicates successful termination */
24
25 } /* end main */
24
Element Value
0 0 Outline
1 0
2 0
3 0
4 0 fig06_03.c
5 0
6 0 (2 of 2 )
7 0
8 0
9 0
1 /* Fig. 6.4: fig06_04.c 25
2 Initializing an array with an initializer list */
3 #include <stdio.h>
Outline
4
5 /* function main begins program execution */
6 int main( void )
7 { fig06_04.c
8 /* use initializer list to initialize array n */
9 int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 }; (1 of 2 )
10 int i; /* counter */
11
12 printf( "%s%13s\n", "Element", "Value" );
13
初始值串列會同時將所有的陣列
14 /* output contents of array in tabular format */ 元素初始化
15 for ( i = 0; i < 10; i++ ) {
16 printf( "%7d%13d\n", i, n[ i ] );
17 } /* end for */
18
19 return 0; /* indicates successful termination */
20
21 } /* end main */
26
Element Value
0 32 Outline
1 27
2 64
3 18
4 95 fig06_04.c
5 14
6 90
7 70
(2 of 2 )
8 60
9 37
1 /* Fig. 6.5: fig06_05.c 27
2 Initialize the elements of array s to the even integers from 2 to 20 */
3 #include <stdio.h>
Outline
4 #define SIZE 10 /* maximum size of array */ #define 命令會告訴編譯器將程式中出現SIZE 的
5 位置都替換為10
6 /* function main begins program execution */
fig06_05.c
7 int main( void )
8 {
9 /* symbolic constant SIZE can be used to specify array size */
(1 of 2 )
10 int s[ SIZE ]; /* array s has SIZE elements */ 編譯器將SIZE替換為 10 ,因此陣列
11 int j; /* counter */ s 有10個元素
12
13 for ( j = 0; j < SIZE; j++ ) { /* set the values */
14 s[ j ] = 2 + 2 * j; for迴圈分別初始化每個元素
15 } /* end for */
16
17 printf( "%s%13s\n", "Element", "Value" );
18
19 /* output contents of array s in tabular format */
20 for ( j = 0; j < SIZE; j++ ) {
21 printf( "%7d%13d\n", j, s[ j ] );
22 } /* end for */
23
24 return 0; /* indicates successful termination */
25
26 } /* end main */
28
Element Value
0 2 Outline
1 4
2 6
3 8
4 10 fig06_05.c
5 12
6 14 (2 of 2 )
7 16
8 18
9 20
1 /* Fig. 6.6: fig06_06.c 29
2 Compute the sum of the elements of the array */
3 #include <stdio.h>
Outline
4 #define SIZE 12
5
6 /* function main begins program execution */
fig06_06.c
7 int main( void )
8 {
9 /* use initializer list to initialize array */
10 int a[ SIZE ] = { 1, 3, 5, 4, 7, 2, 99, 16, 45, 67, 89, 45 };
11 int i; /* counter */
12 int total = 0; /* sum of array */ 初始值串列會同時將所有陣列元
13 素初始化
14 /* sum contents of array a */
15 for ( i = 0; i < SIZE; i++ ) {
16 total += a[ i ]; for迴圈將陣列的每個元素加到
17 } /* end for */ 變數 total中
18
19 printf( "Total of array element values is %d\n", total );
20
21 return 0; /* indicates successful termination */
22
23 } /* end main */

Total of array element values is 383


1 /* Fig. 6.8: fig06_08.c 30
2 Histogram printing program */
3 #include <stdio.h>
Outline
4 #define SIZE 10
5
6 /* function main begins program execution */
fig06_08.c
7 int main( void )
8 {
9 /* use initializer list to initialize array n */
(1 of 2 )
10 int n[ SIZE ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 };
11 int i; /* outer for counter for array elements */
12 int j; /* inner for counter counts *s in each histogram bar */
13
14 printf( "%s%13s%17s\n", "Element", "Value", "Histogram" );
15
16 /* for each element of array n, output a bar of the histogram */
17 for ( i = 0; i < SIZE; i++ ) {
18 printf( "%7d%13d ", i, n[ i ]) ;
19
20 for ( j = 1; j <= n[ i ]; j++ ) { /* print one bar */
21 printf( "%c", '*' );
巢狀的 for 迴圈會在第 i 行印出
22 } /* end inner for */ n[ i ] 個星號
23
24 printf( "\n" ); /* end a histogram bar */
25 } /* end outer for */
26
27 return 0; /* indicates successful termination */
28
29 } /* end main */
31
Element Value Histogram
0 19 ******************* Outline
1 3 ***
2 15 ***************
3 7 *******
4 11 *********** fig06_08.c
5 9 *********
6 13 ************* (2 of 2 )
7 5 *****
8 17 *****************
9 1 *
1 /* Fig. 6.9: fig06_09.c 32
2 Roll a six-sided die 6000 times */
3 #include <stdio.h>
Outline
4 #include <stdlib.h>
5 #include <time.h>
6 #define SIZE 7
fig06_09.c
7
8 /* function main begins program execution */
9 int main( void )
(1 of 2 )
10 {
11 int face; /* random die value 1 - 6 */
12 int roll; /* roll counter 1-6000 */
13 int frequency[ SIZE ] = { 0 }; /* clear counts */
14
15 srand( time( NULL ) ); /* seed random-number generator */
16
17 /* roll die 6000 times */
18 for ( roll = 1; roll <= 6000; roll++ ) {
19 face = 1 + rand() % 6;
20 ++frequency[ face ]; /* replaces 26-line switch of Fig. 5.8 */
21 } /* end for */

for迴圈使用一個陣列來記錄各種
點數出現的次數,以替代六個
變數和一個switch敘述式
22 33
23 printf( "%s%17s\n", "Face", "Frequency" );
24
Outline
25 /* output frequency elements 1-6 in tabular format */
26 for ( face = 1; face < SIZE; face++ ) {
27 printf( "%4d%17d\n", face, frequency[ face ] );
fig06_09.c
28 } /* end for */
29
30 return 0; /* indicates successful termination */
(2 of 2 )
31
32 } /* end main */

Face Frequency
1 1029
2 951
3 987
4 1033
5 1010
6 990
34

C Program Design
C Arrays
▪Static Arrays
35

6.4 使用陣列的例子
▪ 字元陣列
– 字串 “first”實際上是字元所組成的靜態陣列
– 字元陣列可以利用字串常數來初始化
char string1[] = "first";
- 空字元‘\0’ 用來結束字串
- string1 實際上具有六個元素
它等於
char string1[] = { 'f', 'i', 'r', 's', 't', '\0' };
– 可以存取個別的字元
string1[ 3 ] 是 ‘s’
– 陣列名稱是陣列的位址,因此在使用scanf時不需要&
scanf( "%s", string2 );
- 讀入字元,直到遇到一個空白字元
- 小心不要讀取超過陣列末端(有可能會發生)
1 /* Fig. 6.10: fig06_10.c 36
2 Treating character arrays as strings */
3 #include <stdio.h>
Outline
4
5 /* function main begins program execution */
6 int main( void )
fig06_10.c
7 {
8 char string1[ 20 ]; /* reserves 20 characters */
9 char string2[] = "string literal"; /* reserves 15 characters */
(1 of 2 )
10 int i; /* counter */
string2陣列替每個字元定義一個元
11
12 /* read string from user into array string1 */
素,因此共有15個元素(包括/0 )
13 printf("Enter a string: ");
14 scanf( "%s", string1 ); /* input ended by whitespace character */
15
16 /* output strings */
17 printf( "string1 is: %s\nstring2 is: %s\n"
18 "string1 with spaces between characters is:\n",
19 string1, string2 );
20
21 /* output characters until null character is reached */
22 for ( i = 0; string1[ i ] != '\0'; i++ ) {
for迴圈將 string1陣列的每個元素印出
23 printf( "%c ", string1[ i ] );
24 } /* end for */ 來,中間隔一個空白
25
26 printf( "\n" );
27
28 return 0; /* indicates successful termination */
29
30 } /* end main */
37
Enter a string: Hello there
string1 is: Hello Outline
string2 is: string literal
string1 with spaces between characters is:
H e l l o
fig06_10.c

(2 of 2 )
1 /* Fig. 6.11: fig06_11.c 38
2 Static arrays are initialized to zero */
3 #include <stdio.h>
Outline
4
5 void staticArrayInit( void ); /* function prototype */
6 void automaticArrayInit( void ); /* function prototype */
fig06_11.c
7
8 /* function main begins program execution */
9 int main( void )
(1 of 4 )
10 {
11 printf( "First call to each function:\n" );
12 staticArrayInit();
13 automaticArrayInit();
14
15 printf( "\n\nSecond call to each function:\n" );
16 staticArrayInit();
17 automaticArrayInit();
18
19 return 0; /* indicates successful termination */
20
21 } /* end main */
22
23 /* function to demonstrate a static local array */ 39
24 void staticArrayInit( void )
25 {
Outline
26 /* initializes elements to 0 first time function is called */
27 static int array1[ 3 ];
static陣列只會建立一次(當
28 int i; /* counter */
staticArrayInit 第一次被呼叫的 fig06_11.c
29
30 printf( "\nValues on entering 時候)
staticArrayInit:\n" );
31
(2 of 4 )
32 /* output contents of array1 */
33 for ( i = 0; i <= 2; i++ ) {
34 printf( "array1[ %d ] = %d ", i, array1[ i ] );
35 } /* end for */
36
37 printf( "\nValues on exiting staticArrayInit:\n" );
38
39 /* modify and output contents of array1 */
40 for ( i = 0; i <= 2; i++ ) {
41 printf( "array1[ %d ] = %d ", i, array1[ i ] += 5 );
42 } /* end for */
43
44 } /* end function staticArrayInit */
45 40
46 /* function to demonstrate an automatic local array */
47 void automaticArrayInit( void )
Outline
48 {
49 /* initializes elements each time function is called */
50 int array2[ 3 ] = { 1, 2, 3 };
每次呼叫 automaticArrayInit 時, fig06_11.c
51 int i; /* counter */
52 都會重新建立自動變數
53 printf( "\n\nValues on entering automaticArrayInit:\n" );
(3 of 4 )
54
55 /* output contents of array2 */
56 for ( i = 0; i <= 2; i++ ) {
57 printf("array2[ %d ] = %d ", i, array2[ i ] );
58 } /* end for */
59
60 printf( "\nValues on exiting automaticArrayInit:\n" );
61
62 /* modify and output contents of array2 */
63 for ( i = 0; i <= 2; i++ ) {
64 printf( "array2[ %d ] = %d ", i, array2[ i ] += 5 );
65 } /* end for */
66
67 } /* end function automaticArrayInit */
41
First call to each function:
Outline
Values on entering staticArrayInit:
array1[ 0 ] = 0 array1[ 1 ] = 0 array1[ 2 ] = 0
Values on exiting staticArrayInit:
array1[ 0 ] = 5 array1[ 1 ] = 5 array1[ 2 ] = 5 fig06_11.c

Values on entering automaticArrayInit: (4 of 4 )


array2[ 0 ] = 1 array2[ 1 ] = 2 array2[ 2 ] = 3
Values on exiting automaticArrayInit:
array2[ 0 ] = 6 array2[ 1 ] = 7 array2[ 2 ] = 8

Second call to each function:

Values on entering staticArrayInit:


array1[ 0 ] = 5 array1[ 1 ] = 5 array1[ 2 ] = 5
Values on exiting staticArrayInit:
array1[ 0 ] = 10 array1[ 1 ] = 10 array1[ 2 ] = 10

Values on entering automaticArrayInit:


array2[ 0 ] = 1 array2[ 1 ] = 2 array2[ 2 ] = 3
Values on exiting automaticArrayInit:
array2[ 0 ] = 6 array2[ 1 ] = 7 array2[ 2 ] = 8
42

C Program Design
C Arrays

▪Passing Arrays to Functions


43

6.5 Passing Arrays to Functions

▪ To pass an array argument to a function, specify the


name of the array without any brackets
▪ Array size usually passed to function, e.g.,
int myArray[ 24 ];
myFunction( myArray, 24 );
▪ In C, array’s name denotes the starting address
(reference) of the array
▪ Hence, the above function call is equivalent to
myFunction( &myArray[0], 24 );
▪ Modifying the array element in the function, the original
element is modified
44

6.5 Passing Arrays to Functions

▪ Passing the array’s reference to functions makes sense


for performance reasons
– Remark: call this as call-by-reference is, in fact, improper
since this is not done by compiler

▪ 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.
45

Function Prototypes with Arrays

void myFunction( int array[], int arraySize );

void myFunction( int[], int );


1 /* Fig. 6.12: fig06_12.c 46
2 The name of an array is the same as &array[ 0 ] */
3 #include <stdio.h>
Outline
4
5 /* function main begins program execution */
6 int main( void )
fig06_12.c
7 {
8 char array[ 5 ]; /* define an array of size 5 */
9
10 printf( " array = %p\n&array[0] = %p\n &array = %p\n",
11 array, &array[ 0 ], &array );
12
13 return 0; /* indicates successful termination */
14
15 } /* end main */

array = 0012FF78
&array[0] = 0012FF78
&array = 0012FF78
47

Example #include <stdio.h>

void listElements(int[], int);


void RemoveFactor5(int[], int);

main()
{
int data[]={12, 55, 6, 21, 35, 90, 91};

printf("Original elements in data[] are: \n");


listElements(data, sizeof(data)/sizeof(int));

RemoveFactor5(data, sizeof(data)/sizeof(int));

printf("\n\nRemoving factor 5, elements in data[] become:\n");


listElements(data, sizeof(data)/sizeof(int));
將一正整數陣 printf("\n");
}
列中之各元素
void listElements(int vals[], int size)
移除因子5 {
int i;

for(i=0; i<size; i++) printf("%d ", vals[i]);


}

void RemoveFactor5(int vals[], int size)


{
int i;

for(i=0; i<size; i++)


while(vals[i] % 5 == 0 && vals[i] > 0) vals[i] /= 5;
}
48

Example #include <stdio.h>

void listElements(int[], int);


void RemoveFactor5(int[], int);

main()
{
int data[]={12, 55, 6, 21, 35, 90, 91};

printf("Original elements in data[] are: \n");


listElements(data, sizeof(data)/sizeof(int));

RemoveFactor5(data, sizeof(data)/sizeof(int));

printf("\n\nRemoving factor 5, elements in data[] become:\n");


listElements(data, sizeof(data)/sizeof(int));
將一正整數陣 printf("\n");
}
列中之各元素
void listElements(int vals[], int size)
移除因子5 {
int i;

for(i=0; i<size; i++) printf("%d ", vals[i]);


}

void RemoveFactor5(int vals[], int size)


{
int i;

for(i=0; i<size; i++)


while(vals[i] % 5 == 0 && vals[i] > 0) vals[i] /= 5;
}
1 /* Fig. 6.13: fig06_13.c 49
2 Passing arrays and individual array elements to functions */
3 #include <stdio.h>
Outline
4 #define SIZE 5
5
6 /* function prototypes */
fig06_13.c
7 void modifyArray( int b[], int size ); 函式原型指出此函式會接
8 void modifyElement( int e ); 收一個陣列 (1 of 3 )
9
10 /* function main begins program execution */
11 int main( void )
12 {
13 int a[ SIZE ] = { 0, 1, 2, 3, 4 }; /* initialize a */
14 int i; /* counter */
15
16 printf( "Effects of passing entire array by reference:\n\nThe "
17 "values of the original array are:\n" );
18
19 /* output original array */
20 for ( i = 0; i < SIZE; i++ ) {
21 printf( "%3d", a[ i ] );
22 } /* end for */
23
24 printf( "\n" );
25
26 /* pass array a to modifyArray by reference */
只傳遞陣列名稱,即可將陣列a傳
27 modifyArray( a, SIZE );
28
遞給modifyArray
29 printf( "The values of the modified array are:\n" );
30
31 /* output modified array */ 50
32 for ( i = 0; i < SIZE; i++ ) {
33 printf( "%3d", a[ i ] );
Outline
34 } /* end for */
35
36 /* output value of a[ 3 ] */
fig06_13.c
37 printf( "\n\n\nEffects of passing array element "
38 "by value:\n\nThe value of a[3] is %d\n", a[ 3 ] );
39
(2 of 3 )
40 modifyElement( a[ 3 ] ); /* pass array element a[ 3 ] by value */
41
42 /* output value of a[ 3 ] */ 傳遞 a[ 3 ],將陣列元素傳遞給
43 printf( "The value of a[ 3 ] is %d\n", a[ 3 ] ); modifyElement
44
45 return 0; /* indicates successful termination */
46
47 } /* end main */
48
49 /* in function modifyArray, "b" points to the original array "a"
50 in memory */
51 void modifyArray( int b[], int size )
52 {
53 int j; /* counter */
54
55 /* multiply each array element by 2 */
56 for ( j = 0; j < size; j++ ) {
57 b[ j ] *= 2;
58 } /* end for */
59
60 } /* end function modifyArray */
61 51
62 /* in function modifyElement, "e" is a local copy of array element
63 a[ 3 ] passed from main */
Outline
64 void modifyElement( int e )
65 {
66 /* multiply parameter by 2 */
fig06_13.c
67 printf( "Value in modifyElement is %d\n", e *= 2 );
68 } /* end function modifyElement */
(3 of 3 )
Effects of passing entire array by reference:

The values of the original array are:


0 1 2 3 4
The values of the modified array are:
0 2 4 6 8

Effects of passing array element by value:

The value of a[3] is 6


Value in modifyElement is 12
The value of a[ 3 ] is 6
1 /* Fig. 6.14: fig06_14.c 52
2 Demonstrating the const type qualifier with arrays */
3 #include <stdio.h>
Outline
4
5 void tryToModifyArray( const int b[] ); /* function prototype */
6
fig06_14.c
7 /* function main begins program execution */
8 int main( void )
9 {
(1 of 2 )
10 int a[] = { 10, 20, 30 }; /* initialize a */ const修飾詞告訴編譯器,陣列不
11
能被更改
12 tryToModifyArray( a );
13
14 printf("%d %d %d\n", a[ 0 ], a[ 1 ], a[ 2 ] );
15
16 return 0; /* indicates successful termination */
17
18 } /* end main */
19
20 /* in function tryToModifyArray, array b is const, so it cannot be
21 used to modify the original array a in main. */
22 void tryToModifyArray( const int b[] )
23 {
24 b[ 0 ] /= 2; /* error */ 任何嘗試更改陣列的動作都會導致
25 b[ 1 ] /= 2; /* error */
錯誤
26 b[ 2 ] /= 2; /* error */
27 } /* end function tryToModifyArray */
53
Compiling...
FIG06_14.C Outline
fig06_14.c(24) : error C2166: l-value specifies const object
fig06_14.c(25) : error C2166: l-value specifies const object
fig06_14.c(26) : error C2166: l-value specifies const object
fig06_14.c

(2 of 2 )
54

C Program Design
C Arrays

▪Array Examples
55

Search array
▪ 判斷陣列中是否含有某關鍵值
▪ 線性搜尋(linear search)
– 簡單
– 將陣列中的每一個元素與關鍵值互相比較
– 對於小型的陣列或未排序過的陣列而言,線性搜尋是很有
用的
1 /* Fig. 6.18: fig06_18.c 56
2 Linear search of an array */
3 #include <stdio.h>
Outline
4 #define SIZE 100
5
6 /* function prototype */
fig06_18.c
7 int linearSearch( const int array[], int key, int size );
8
9 /* function main begins program execution */
(1 of 3 )
10 int main( void )
11 {
12 int a[ SIZE ]; /* create array a */
13 int x; /* counter for initializing elements 0-99 of array a */
14 int searchKey; /* value to locate in array a */
15 int element; /* variable to hold location of searchKey or -1 */
16
17 /* create data */
18 for ( x = 0; x < SIZE; x++ ) {
19 a[ x ] = 2 * x;
20 } /* end for */
21
22 printf( "Enter integer search key:\n" ); 57
23 scanf( "%d", &searchKey );
24
Outline
25 /* attempt to locate searchKey in array a */
26 element = linearSearch( a, searchKey, SIZE );
27
fig06_18.c
28 /* display results */
29 if ( element != -1 ) {
30 printf( "Found value in element %d\n", element );
(2 of 3 )
31 } /* end if */
32 else {
33 printf( "Value not found\n" );
34 } /* end else */
35
36 return 0; /* indicates successful termination */
37
38 } /* end main */
39
40 /* compare key to every element of array until the location is found
41 or until the end of array is reached; return subscript of element
42 if key or -1 if key is not found */
43 int linearSearch( const int array[], int key, int size )
44 {
45 int n; /* counter */
46
47 /* loop through array */ 58
48 for ( n = 0; n < size; ++n ) {
49
Outline
50 if ( array[ n ] == key ) {
51 return n; /* return location of key */
52 } /* end if */
線性搜尋演算法會搜尋陣列中的 fig06_18.c
53
54 } /* end for */ 每一個元素,直到找到符合的
55 為止 (3 of 3 )
56 return -1; /* key not found */
57
58 } /* end function linearSearch */

Enter integer search key:


36
Found value in element 18

Enter integer search key:


37
Value not found
59

Example // MinMax.c
#include <stdio.h>
#include <limits.h>

#define MAX_NUM_ELEMENTS 50

int ReadData(int[], int);

main()
{
int data[MAX_NUM_ELEMENTS];
int i, count;
int min = INT_MAX, max = INT_MIN;

count = ReadData(data, MAX_NUM_ELEMENTS);

搜尋最大值 for(i = 0; i < count; i++){


if(min > data[i]) min = data[i];
與最小值 if(max < data[i]) max = data[i];
}

printf("min=%d and max=%d\n", min, max);


}

int ReadData(int data[], int size)


{
int count=0;

while(count < size && scanf("%d", &data[count]) != EOF)


count++;

return count;
}
60

Example // MinMax.c
#include <stdio.h>
#include <limits.h>

#define MAX_NUM_ELEMENTS 50

int ReadData(int[], int);

main()
{
int data[MAX_NUM_ELEMENTS];
int i, count;
int min = INT_MAX, max = INT_MIN;

count = ReadData(data, MAX_NUM_ELEMENTS);

搜尋最大值 for(i = 0; i < count; i++){


if(min > data[i]) min = data[i];
與最小值 if(max < data[i]) max = data[i];
}

printf("min=%d and max=%d\n", min, max);


}

int ReadData(int data[], int size)


{
int count=0;

while(count < size && scanf("%d", &data[count]) != EOF)


count++;

return count;
}
61
6.6 Sorting
▪ 排序資料
– 電腦最重要的應用之一
– 差不多每一個組織都必須排序資料
▪ 氣泡排序(bubble sort、sinking sort)
– 會對陣列處理數個回合
– 比較相鄰的一對元素
- 如果此對元素為遞增順序(或相等)的話,則將他們維持現

- 如果這對元素為遞減順序的話,便將他們的值對調過來
– 重複
▪ 範例:
– 原始陣列: 3 4 2 6 7
– 第一回合: 3 2 4 6 7
– 第二回合: 2 3 4 6 7
– 較小的元素會如氣泡浮出水面一樣,慢慢地上升至陣列的頂點
62

Bubble Sort
63

Bubble Sort

http://www.solidware.com/sort/
64

Bubble Sort (I)

void BubbleSort(int data[], int n)


{
int tmp, i, j;

for(i=0; i<n-1; i++)


for(j=0; j<n-i-1; j++)
if(data[j] > data[j+1]){
tmp = data[j];
data[j] = data[j+1];
data[j+1] = tmp;
}
}
65

Bubble Sort (II)

void BubbleSort(int data[], int n)


{
{
int
int tmp,
tmp, i,
i, j,
j; sorted;

for(i=0, sorted=FALSE; !sorted && i<n-1; i++)


for(i=0; i<n-1; i++)
for(j=0, sorted=TRUE; j<n-i-1; j++)
for(j=0; j<n-i-1; j++)
if(data[j] > data[j+1]){
if(data[j] > data[j+1]){
tmp = data[j];
tmp = data[j];
data[j] = data[j+1];
data[j] = data[j+1];
data[j+1] = tmp;
data[j+1] = tmp;
sorted = FALSE;
}}
}
66

Binary Search
▪ 二元搜尋(binary search)
– 只能用在已排序的陣列
– 找出陣列的中間元素,將之與搜尋關鍵值作比較
- 如果相等的話,表示已找到要找的元素
- 如果關鍵值小於中間元素,就搜尋陣列的前半部
- 如果關鍵值大於中間元素,就搜尋陣列的後半部
- 重複
– 非常快速;最多 n 個步驟,其中 2n > 元素數量
- 30 個元素的陣列,至多五個步驟
25 > 30 ,因此至多五個步驟
67

Binary Search

int binSearch(int x, int v[], int n);


v[]
0 1
1 5
2 9 6  binSearch(137, v, 11)
3 25
4 80 9  binSearch(201, v, 11)
5 125
6 137
-1  binSearch(45, v, 11)
7 140
8 180
9 201
10 400
68

Binary Search binSearch(25, v, 11)

low <= high


mid = (low + high) / 2 = 5
v[]
low = 0 1
1 5
2 9
v[mid] = 125 > 25
3 25
4 80
mid = 5 125
6 137
7 140
8 180
9 201
high = 10 400
69

Binary Search binSearch(25, v, 11)

v[]
low = 0 1
1 5
2 9
v[mid] = 125 > 25
3 25
high = 4 80
high = mid - 1
mid = 5 125
6 137
7 140
8 180
9 201
10 400
70

Binary Search binSearch(25, v, 11)

low <= high


v[] mid = (low + high) / 2 = 2
low = 0 1
1 5
mid = 2 9
v[mid] = 9 < 25
3 25
high = 4 80
5 125
6 137
7 140
8 180
9 201
10 400
71

Binary Search binSearch(25, v, 11)

v[]
0 1
1 5
mid = 2 9
v[mid] = 9 < 25
low = 3 25
high = 4 80
low = mid + 1
5 125
6 137
7 140
8 180
9 201
10 400
72

Binary Search 3 binSearch(25, v, 11)

low <= high


v[] mid = (low + high) / 2 = 3
0 1
1 5
2 9
v[mid] = 25 == 25
mid = low = 3 25
high = 4 80
5 125
6 137
7 140
8 180
9 201
10 400
73

Binary Search binSearch(45, v, 11)

low <= high


mid = (low + high) / 2 = 5
v[]
low = 0 1
1 5
2 9
v[mid] = 125 > 25
3 25
4 80
mid = 5 125
6 137
7 140
8 180
9 201
high = 10 400
74

Binary Search binSearch(45, v, 11)

v[]
low = 0 1
1 5
2 9
v[mid] = 125 > 45
3 25
high = 4 80
high = mid - 1
mid = 5 125
6 137
7 140
8 180
9 201
10 400
75

Binary Search binSearch(45, v, 11)

low <= high


v[] mid = (low + high) / 2 = 2
low = 0 1
1 5
mid = 2 9
v[mid] = 9 < 45
3 25
high = 4 80
5 125
6 137
7 140
8 180
9 201
10 400
76

Binary Search binSearch(45, v, 11)

v[]
0 1
1 5
mid = 2 9
v[mid] = 9 < 45
low = 3 25
high = 4 80
low = mid + 1
5 125
6 137
7 140
8 180
9 201
10 400
77

Binary Search binSearch(45, v, 11)

low <= high


v[] mid = (low + high) / 2 = 3
0 1
1 5
2 9
v[mid] = 25 < 45
mid = low = 3 25
high = 4 80
5 125
6 137
7 140
8 180
9 201
10 400
78

Binary Search binSearch(45, v, 11)

v[]
0 1
1 5
2 9
v[mid] = 25 < 45
mid = 3 25
low= high = 4 80
low = mid + 1
5 125
6 137
7 140
8 180
9 201
10 400
79

Binary Search binSearch(45, v, 11)

low <= high


v[] mid = (low + high) / 2 = 4
0 1
1 5
2 9
v[mid] = 80 > 45
3 25
low= high = 4 80
5 125
6 137
7 140
8 180
9 201
10 400
80

Binary Search binSearch(45, v, 11)

v[]
0 1
1 5
2 9
v[mid] = 80 > 45
high = 3 25
low= 4 80
high = mid - 1
5 125
6 137
7 140
8 180
9 201
10 400
81

Binary Search
-1  binSearch(45, v, 11)


low <= high
v[]
0 1
1 5
2 9
high = 3 25
low= 4 80
5 125
6 137
7 140
8 180
9 201
10 400
82

Example: Binary Search

/* binsearch: find x in v[0] <= v[1] <= ... <= v[n-1] */


int binSearch(int x, const int v[], int n)
{
int low, high, mid;

low = 0;
high = n - 1;
while (low <= high) {
mid = (low+high)/2;
if (x < v[mid])
high = mid - 1;
else if (x > v[mid])
low = mid + 1;
else /* found match */
return mid;
}
return -1; /* no match */
}
83

Example: Binary Search


1 /* Fig. 6.19: fig06_19.c 84
2 Binary search of an array */
3 #include <stdio.h>
Outline
4 #define SIZE 15
5
6 /* function prototypes */
fig06_19.c
7 int binarySearch( const int b[], int searchKey, int low, int high );
8 void printHeader( void );
9 void printRow( const int b[], int low, int mid, int high );
(1 of 6 )
10
11 /* function main begins program execution */
12 int main( void )
13 {
14 int a[ SIZE ]; /* create array a */
15 int i; /* counter for initializing elements 0-14 of array a */
16 int key; /* value to locate in array a */
17 int result; /* variable to hold location of key or -1 */
18
19 /* create data */
20 for ( i = 0; i < SIZE; i++ ) {
21 a[ i ] = 2 * i;
22 } /* end for */
23
24 printf( "Enter a number between 0 and 28: " );
25 scanf( "%d", &key );
26
27 printHeader();
28
29 /* search for key in array a */
30 result = binarySearch( a, key, 0, SIZE - 1 );
31 85
32 /* display results */
33 if ( result != -1 ) {
Outline
34 printf( "\n%d found in array element %d\n", key, result );
35 } /* end if */
36 else {
fig06_19.c
37 printf( "\n%d not found\n", key );
38 } /* end else */
39
(2 of 6 )
40 return 0; /* indicates successful termination */
41
42 } /* end main */
43
44 /* function to perform binary search of an array */
45 int binarySearch( const int b[], int searchKey, int low, int high )
46 {
47 int middle; /* variable to hold middle element of array */
48
49 /* loop until low subscript is greater than high subscript */
50 while ( low <= high ) {
51
52 /* determine middle element of subarray being searched */
53 middle = ( low + high ) / 2;
54
55 /* display subarray used in this loop iteration */
56 printRow( b, low, middle, high );
57
58 /* if searchKey matched middle element, return middle */ 86
59 if ( searchKey == b[ middle ] ) {
return middle;
Outline
60 假如找到了,就傳回索引
61 } /* end if */
62
63 /* if searchKey less than middle element, set new high */
fig06_19.c
64 else if ( searchKey < b[ middle ] ) {
65 high = middle - 1; /* search low end of array */
66 } /* end else if */
(3 of 6 )
67 假如數值太大,就尋找陣列的左半部
68 /* if searchKey greater than middle element, set new low */
69 else {
70 low = middle + 1; /* search high end of array */
71 } /* end else */
72 假如數值太小,就尋找陣列的右半部
73 } /* end while */
74
75 return -1; /* searchKey not found */
76
77 } /* end function binarySearch */
78
79 /* Print a header for the output */
80 void printHeader( void )
81 {
82 int i; /* counter */
83
84 printf( "\nSubscripts:\n" );
85
86 /* output column head */ 87
87 for ( i = 0; i < SIZE; i++ ) {
88 printf( "%3d ", i );
Outline
89 } /* end for */
90
91 printf( "\n" ); /* start new line of output */
fig06_19.c
92
93 /* output line of - characters */
94 for ( i = 1; i <= 4 * SIZE; i++ ) {
(4 of 6 )
95 printf( "-" );
96 } /* end for */
97
98 printf( "\n" ); /* start new line of output */
99 } /* end function printHeader */
100
101 /* Print one row of output showing the current
102 part of the array being processed. */
103 void printRow( const int b[], int low, int mid, int high )
104 {
105 int i; /* counter for iterating through array b */
106
107 /* loop through entire array */ 88
108 for ( i = 0; i < SIZE; i++ ) {
109
Outline
110 /* display spaces if outside current subarray range */
111 if ( i < low || i > high ) {
112 printf( " " );
fig06_19.c
113 } /* end if */
114 else if ( i == mid ) { /* display middle element */
115 printf( "%3d*", b[ i ] ); /* mark middle value */
(5 of 6 )
116 } /* end else if */
117 else { /* display other elements in subarray */
118 printf( "%3d ", b[ i ] );
119 } /* end else */
120
121 } /* end for */
122
123 printf( "\n" ); /* start new line of output */
124 } /* end function printRow */

Enter a number between 0 and 28: 25

Subscripts:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
------------------------------------------------------------
0 2 4 6 8 10 12 14* 16 18 20 22 24 26 28
16 18 20 22* 24 26 28
24 26* 28
24*

25 not found
(continued on next slide… )
(continued from previous slide…) 89
Enter a number between 0 and 28: 8 Outline
Subscripts:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
------------------------------------------------------------ fig06_19.c
0 2 4 6 8 10 12 14* 16 18 20 22 24 26 28
0 2 4 6* 8 10 12
8 10* 12
(6 of 6 )
8*

8 found in array element 4

Enter a number between 0 and 28: 6

Subscripts:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
------------------------------------------------------------
0 2 4 6 8 10 12 14* 16 18 20 22 24 26 28
0 2 4 6* 8 10 12

6 found in array element 3


90

6.7 範例研究:使用陣列來計算平均數、
中位數以及眾數
▪ Mean – 平均數
▪ Median –中位數,已排序串列的中間元素
– 1, 2, 3, 4, 5
– 3 是中位數
▪ Mode –眾數,出現頻率最高的數值
– 1, 1, 1, 2, 3, 3, 4, 5
– 1 是眾數
1 /* Fig. 6.16: fig06_16.c 91
2 This program introduces the topic of survey data analysis.
3 It computes the mean, median and mode of the data */
Outline
4 #include <stdio.h>
5 #define SIZE 99
6
fig06_16.c
7 /* function prototypes */
8 void mean( const int answer[] );
9 void median( int answer[] );
(1 of 6 )
10 void mode( int freq[], const int answer[] ) ;
11 void bubbleSort( int a[] );
12 void printArray( const int a[] );
13
14 /* function main begins program execution */
15 int main( void )
16 {
17 int frequency[ 10 ] = { 0 }; /* initialize array frequency */
18
19 /* initialize array response */
20 int response[ SIZE ] =
21 { 6, 7, 8, 9, 8, 7, 8, 9, 8, 9,
22 7, 8, 9, 5, 9, 8, 7, 8, 7, 8,
23 6, 7, 8, 9, 3, 9, 8, 7, 8, 7,
24 7, 8, 9, 8, 9, 8, 9, 7, 8, 9,
25 6, 7, 8, 7, 8, 7, 9, 8, 9, 2,
26 7, 8, 9, 8, 9, 8, 9, 7, 5, 3,
27 5, 6, 7, 2, 5, 3, 9, 4, 6, 4,
28 7, 8, 9, 6, 8, 7, 8, 9, 7, 8,
29 7, 4, 4, 2, 5, 3, 8, 7, 5, 6,
30 4, 5, 6, 1, 6, 5, 7, 8, 7 };
31 92
32 /* process responses */
33 mean( response );
Outline
34 median( response );
35 mode( frequency, response );
36
fig06_16.c
37 return 0; /* indicates successful termination */
38
39 } /* end main */
(2 of 6 )
40
41 /* calculate average of all response values */
42 void mean( const int answer[] )
43 {
44 int j; /* counter for totaling array elements */
45 int total = 0; /* variable to hold sum of array elements */
46
47 printf( "%s\n%s\n%s\n", "********", " Mean", "********" );
48
49 /* total response values */
50 for ( j = 0; j < SIZE; j++ ) {
51 total += answer[ j ];
52 } /* end for */
53
54 printf( "The mean is the average value of the data\n"
55 "items. The mean is equal to the total of\n"
56 "all the data items divided by the number\n"
57 "of data items ( %d ). The mean value for\n"
58 "this run is: %d / %d = %.4f\n\n",
59 SIZE, total, SIZE, ( double ) total / SIZE );
60 } /* end function mean */
61 93
62 /* sort array and determine median element's value */
63 void median( int answer[] )
Outline
64 {
65 printf( "\n%s\n%s\n%s\n%s",
66 "********", " Median", "********",
fig06_16.c
67 "The unsorted array of responses is" );
68
69 printArray( answer ); /* output unsorted array */
(3 of 6 )
70
71 bubbleSort( answer ); /* sort array */ 當陣列已排序時,中位數是中間的元素
72
73 printf( "\n\nThe sorted array is" );
74 printArray( answer ); /* output sorted array */
75
76 /* display median element */
77 printf( "\n\nThe median is element %d of\n"
78 "the sorted %d element array.\n"
79 "For this run the median is %d\n\n",
80 SIZE / 2, SIZE, answer[ SIZE / 2 ] );
81 } /* end function median */
82
83 /* determine most frequent response */
84 void mode( int freq[], const int answer[] )
85 {
86 int rating; /* counter for accessing elements 1-9 of array freq */
87 int j; /* counter for summarizing elements 0-98 of array answer */
88 int h; /* counter for diplaying histograms of elements in array freq */
89 int largest = 0; /* represents largest frequency */
90 int modeValue = 0; /* represents most frequent response */
91 94
92 printf( "\n%s\n%s\n%s\n",
93 "********", " Mode", "********" );
Outline
94
95 /* initialize frequencies to 0 */
96 for ( rating = 1; rating <= 9; rating++ ) {
fig06_16.c
97 freq[ rating ] = 0;
98 } /* end for */
99
(4 of 6 )
100 /* summarize frequencies */
101 for ( j = 0; j < SIZE; j++ ) {
102 ++freq[ answer[ j ] ];
103 } /* end for */
104
105 /* output headers for result columns */
106 printf( "%s%11s%19s\n\n%54s\n%54s\n\n",
107 "Response", "Frequency", "Histogram",
108 "1 1 2 2", "5 0 5 0 5" );
109
110 /* output results */
111 for ( rating = 1; rating <= 9; rating++ ) {
112 printf( "%8d%11d ", rating, freq[ rating ] );
113
114 /* keep track of mode value and largest frequency value */
115 if ( freq[ rating ] > largest ) {
116 largest = freq[ rating ];
117 modeValue = rating;
118 } /* end if */
119 95
120 /* output histogram bar representing frequency value */
121 for ( h = 1; h <= freq[ rating ]; h++ ) {
Outline
122 printf( "*" );
123 } /* end inner for */
124
fig06_16.c
125 printf( "\n" ); /* being new line of output */
126 } /* end outer for */
127
(5 of 6 )
128 /* display the mode value */
129 printf( "The mode is the most frequent value.\n"
130 "For this run the mode is %d which occurred"
131 " %d times.\n", modeValue, largest );
132 } /* end function mode */
133
134 /* function that sorts an array with bubble sort algorithm */
135 void bubbleSort( int a[] )
136 {
137 int pass; /* pass counter */
138 int j; /* comparison counter */
139 int hold; /* temporary location used to swap elements */
140
141 /* loop to control number of passes */
142 for ( pass = 1; pass < SIZE; pass++ ) {
143
144 /* loop to control number of comparisons per pass */
145 for ( j = 0; j < SIZE - 1; j++ ) {
146
147 /* swap elements if out of order */ 96
148 if ( a[ j ] > a[ j + 1 ] ) {
149 hold = a[ j ];
Outline
150 a[ j ] = a[ j + 1 ];
151 a[ j + 1 ] = hold;
152 } /* end if */
fig06_16.c
153
154 } /* end inner for */
155
(6 of 6 )
156 } /* end outer for */
157
158 } /* end function bubbleSort */
159
160 /* output array contents (20 values per row) */
161 void printArray( const int a[] )
162 {
163 int j; /* counter */
164
165 /* output array contents */
166 for ( j = 0; j < SIZE; j++ ) {
167
168 if ( j % 20 == 0 ) { /* begin new line every 20 values */
169 printf( "\n" );
170 } /* end if */
171
172 printf( "%2d", a[ j ] );
173 } /* end for */
174
175 } /* end function printArray */
******** 97
Mean
******** Outline
The mean is the average value of the data
items. The mean is equal to the total of
all the data items divided by the number
of data items ( 99 ). The mean value for
this run is: 681 / 99 = 6.8788

******** (1 of 2 )
Median
********
The unsorted array of responses is
6 7 8 9 8 7 8 9 8 9 7 8 9 5 9 8 7 8 7 8
6 7 8 9 3 9 8 7 8 7 7 8 9 8 9 8 9 7 8 9
6 7 8 7 8 7 9 8 9 2 7 8 9 8 9 8 9 7 5 3
5 6 7 2 5 3 9 4 6 4 7 8 9 6 8 7 8 9 7 8
7 4 4 2 5 3 8 7 5 6 4 5 6 1 6 5 7 8 7

The sorted array is


1 2 2 2 3 3 3 3 4 4 4 4 4 5 5 5 5 5 5 5
5 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7
7 7 7 7 7 7 7 7 7 7 7 7 7 8 8 8 8 8 8 8
8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
(continued on next slide… )
(continued from previous slide…) 98
The median is element 49 of
the sorted 99 element array. Outline
For this run the median is 7

********
Mode
********
Response Frequency Histogram

1 1 2 2 (2 of 2 )
5 0 5 0 5

1 1 *
2 3 ***
3 4 ****
4 5 *****
5 8 ********
6 9 *********
7 23 ***********************
8 27 ***************************
9 19 *******************
The mode is the most frequent value.
For this run the mode is 8 which occurred 27 times.
99

C Program Design
C Arrays

▪Multi-dimensional Arrays
100

6.9 Multi-dimensional Arrays

▪ 多維陣列
– 具有列(rows)和行(columns)的表格 (m x n 陣列)
– 類似矩陣: 先指定列,再指定行
▪ 初始化
– int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
– 初始值會以列為單位,並且用大括號括起來
– 假如初始值不夠,剩餘的元素會被設為0
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
▪ 引用元素
– 指定列,然後再指定行
printf( "%d", b[ 0 ][ 1 ] );
101

Example

#define MONTHS 12
#define YEARS 5

int main(void)
{
float rainFall[YEARS][MONTHS];
int i, j;

for ( i = 0; i < YEARS; i++ ) {


for ( j = 0; j < MONTHS; j++ ) {
printf( "Rain fall for year %d, month %d: ", i, j );
scanf( "%f", &rainFall[i][j] );
}
}
// . . .
}
#define YEARS 5 102
#define MONTHS 12
2D-Arrays in Memory
float rainFall[YEARS][MONTHS];

Physical View
rainFall, rainFall[0] rainFall[0][0]
rainFall[0][1]
rainFall[0][2]
. . .

Logical View
rainFall[0][11]
rainFall[1] rainFall[1][0]
rainFall[1][1]
rainFall rainFall[1][2]
. . .
rainFall[0] rainFall[0][0] rainFall[0][1] rainFall[0][2] . . . rainFall[0][11] rainFall[1][11]
rainFall[2] rainFall[2][0]
rainFall[1] rainFall[1][0] rainFall[1][1] rainFall[1][2] . . . rainFall[1][11] rainFall[2][1]
rainFall[2][2]
rainFall[2] rainFall[2][0] rainFall[2][1] rainFall[2][2] . . . rainFall[2][11] . . .
rainFall[2][11]
rainFall[3] rainFall[3][0] rainFall[3][1] rainFall[3][2] . . . rainFall[3][11] rainFall[3] rainFall[3][0]
rainFall[3][1]
rainFall[4] rainFall[4][0] rainFall[4][1] rainFall[4][2] . . . rainFall[4][11] rainFall[3][2]
. . .
rainFall[3][11]
rainFall[4] rainFall[4][0]
rainFall[4][1]
rainFall[4][2]
. . .
rainFall[4][11]
103
#define YEARS 5
#define MONTHS 12
2D-Arrays in Memory float rainFall[YEARS][MONTHS];

Physical View
rainFall, rainFall[0] rainFall[0][0]
rainFall[0][1]
rainFall[0][2]
. . .

Logical View
rainFall[0][11]
rainFall[1] rainFall[1][0]
rainFall[1][1]
rainFall rainFall[1][2]
. . .
rainFall[0] rainFall[0][0] rainFall[0][1] rainFall[0][2] . . . rainFall[0][11] rainFall[1][11]
rainFall[2] rainFall[2][0]
rainFall[1] rainFall[1][0] rainFall[1][1] rainFall[1][2] . . . rainFall[1][11] rainFall[2][1]
rainFall[2][2]
rainFall[2] rainFall[2][0] rainFall[2][1] rainFall[2][2] . . . rainFall[2][11] . . .
rainFall[2][11]
rainFall[3] rainFall[3][0] rainFall[3][1] rainFall[3][2] . . . rainFall[3][11] rainFall[3] rainFall[3][0]
rainFall[3][1]
rainFall[4] rainFall[4][0] rainFall[4][1] rainFall[4][2] . . . rainFall[4][11] rainFall[3][2]
. . .
rainFall[3][11]
rainFall[4] rainFall[4][0]
rainFall[4][1]
rainFall[4][2]
. . .
rainFall[4][11]
104
#define YEARS 5
#define MONTHS 12
2D-Arrays in Memory float rainFall[YEARS][MONTHS];

Physical View
rainFall, rainFall[0] rainFall[0][0]
rainFall[0][1]
rainFall[0][2]
. . .

Logical View
rainFall[0][11]
rainFall[1] rainFall[1][0]
rainFall[1][1]
rainFall rainFall[1][2]
. . .
rainFall[0] rainFall[0][0] rainFall[0][1] rainFall[0][2] . . . rainFall[0][11] rainFall[1][11]
rainFall[2] rainFall[2][0]
rainFall[1] rainFall[1][0] rainFall[1][1] rainFall[1][2] . . . rainFall[1][11] rainFall[2][1]
rainFall[2][2]
rainFall[2] rainFall[2][0] rainFall[2][1] rainFall[2][2] . . . rainFall[2][11] . . .
rainFall[2][11]
rainFall[3] rainFall[3][0] rainFall[3][1] rainFall[3][2] . . . rainFall[3][11] rainFall[3] rainFall[3][0]
rainFall[3][1]
rainFall[4] rainFall[4][0] rainFall[4][1] rainFall[4][2] . . . rainFall[4][11] rainFall[3][2]
. . .
rainFall[3][11]
rainFall[4] rainFall[4][0]
rainFall[4][1]
rainFall[4][2]
. . .
rainFall[4][11]
105
#define YEARS 5
#define MONTHS 12
2D-Arrays in Memory float rainFall[YEARS][MONTHS];
MONTHS

Physical View

How?
rainFall, rainFall[0] rainFall[0][0]
rainFall[0][1]
rainFall[0][2]
. . .

Logical View
rainFall[0][11]
rainFall[1] rainFall[1][0]
rainFall[1][1]
rainFall rainFall[1][2]
. . .
rainFall[0] rainFall[0][0] rainFall[0][1] rainFall[0][2] . . . rainFall[0][11] rainFall[1][11]
rainFall[2] rainFall[2][0]
rainFall[1] rainFall[1][0] rainFall[1][1] rainFall[1][2] . . . rainFall[1][11] rainFall[2][1]
rainFall[2][2]
rainFall[2] rainFall[2][0] rainFall[2][1] rainFall[2][2] . . . rainFall[2][11] . . .
rainFall[2][11]
rainFall[3] rainFall[3][0] rainFall[3][1] rainFall[3][2] . . . rainFall[3][11] rainFall[3] rainFall[3][0]
rainFall[3][1]
rainFall[4] rainFall[4][0] rainFall[4][1] rainFall[4][2] . . . rainFall[4][11] rainFall[3][2]
. . .
rainFall[3][11]
rainFall[4] rainFall[4][0]
rainFall[4][1]
rainFall[4][2]
. . .
rainFall[4][11]
106

2D-Array Initialization

#include <stdio.h>

main()
{
int array1[2][3] = {{1, 2, 3}, {4, 5, 6}};
int array2[2][3] = {{1, 2, 3}, {4}};
int array3[2][3] = {{1, 2, 3}};

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


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

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


int array8[][3] = {1, 2};
int array9[][3] = {1};

printf("Size of array1 to array9 are:\n"


"%d %d %d %d %d %d %d %d %d\n",
sizeof(array1), sizeof(array2), sizeof(array3),
sizeof(array4), sizeof(array5), sizeof(array6),
sizeof(array7), sizeof(array8), sizeof(array9));
}
107

2D-Array as Function’s Argument

#include <stdio.h>

void listElements(char heading[], int array[2][3])


{
int i, j;

printf(heading);

for(i=0; i<2; i++)


for(j=0; j<3; j++)
printf("%d ", array[i][j]);

printf("\n");
}
108

2D-Array as Function’s Argument

Provide no information to the compiler


for locating array’s elements.
#include <stdio.h>

void listElements(char heading[], int array[2][3])


{
int i, j;

printf(heading);

for(i=0; i<2; i++)


for(j=0; j<3; j++)
printf("%d ", array[i][j]);

printf("\n");
}
109

2D-Array as Function’s Argument

#include <stdio.h>

void listElements(char heading[], int array[][3])


array[2][3])
{
int i, j;

printf(heading);

for(i=0; i<2; i++)


for(j=0; j<3; j++)
printf("%d ", array[i][j]);

printf("\n");
}
110

2D-Array as Function’s Argument


#include <stdio.h>

void listElements(char[], int[][3]);

main()
{
int array1[2][3] = {{1, 2, 3}, {4, 5, 6}};
int array2[2][3] = {{1, 2, 3}, {4}};
int array3[2][3] = {{1, 2, 3}};

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


int array5[][3] = {1, 2, 3, 4};
int array6[][3] = {1, 2, 3};
#include <stdio.h>
int array7[][3] = {{1, 2}, {4}};
int array8[][3] = {1, 2};
int array9[][3] = {1};
void listElements(char heading[], int array[][3])
printf("Size of array1
to array9 are:\n"
{
"%d %d %d %d %d
%d %d %d %d\n",
sizeof(array1),
sizeof(array2), sizeof(array3),
int i, j;
sizeof(array4),
sizeof(array5), sizeof(array6),
sizeof(array7), sizeof(array8), sizeof(array9)
);
printf(heading);
listElements("array1: ", array1);
listElements("array2: ", array2);
listElements("array3: ", array3);
for(i=0; i<2; i++)
listElements("array4: ", array4);
listElements("array5: ", array5);
listElements("array6:for(j=0; j<3; j++)
", array6);
listElements("array7:
listElements("array8:
printf("%d ", array[i][j]);
",
",
array7);
array8);
listElements("array9: ", array9);
}
printf("\n");
}
111

Multidimensional Arrays
▪ A collection of a fixed number of
components arranged in n ( 1) dimensions
– all components are of the same type
– also called n-dimensional arrays

▪ Syntax:
dataType arrayName[intexp1][intexp2]…[intexpn];

where intexp1, intexp2, … are expressions


yielding positive integer values
112

Example:

#define YEARS 5
#define TOTALSALES 10
#define PRODUCTS 5

int main(void)
{
int sales[YEARS][TOTALSALES][PRODUCTS];
int i, j, k;

for ( i = 0; i < YEARS; i++ )


for ( j = 0; j < TOTALSALES; j++ )
for ( k = 0; k < PRODUCTS; k++ ) {
printf("In year %d, the number of items sold by
"sales %d for product is", i, j, k);
scanf( "%d", &sales[i][j][k] );
}
// . . .
}
113

N-Dim Array as Function’s Argument

▪ When declaring a multi-dimensional array as a


formal parameter in a function
– can omit size of first dimension but not other
dimensions
– there is no check if the array indices are within bounds

▪ Passing an array to the function by writing its


name.
– An array’s name represents its address (reference)
114

HW #7
1. Write a C program which output an NN magic square,
where N is an odd integer. An NN magic square has N2
cells that are filled with integers from 1 to N2 , and all
of its column sums, row sums and the two diagonal sums
have the same value.

Reference:
115

HW #7 :Knight’s Tour

⚫ Problem 6.24 of the textbook

You might also like