Lecture 07-1
Lecture 07-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 使用注意事項
▪ 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
▪ 定義多個同樣型別的陣列
– 格式類似一般的變數
– 範例:
int b[ 100 ], x[ 27 ];
16
Defining Arrays
arrayType arrayName[numberOfElements];
Examples:
int c[10];
float myArray[3284];
17
arrayType arrayName[numberOfElements];
Examples:
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 n3[10]={0};
int n4[10];
#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;
#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迴圈使用一個陣列來記錄各種
點數出現的次數,以替代六個
變數和一個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
C Program Design
C Arrays
array = 0012FF78
&array[0] = 0012FF78
&array = 0012FF78
47
main()
{
int data[]={12, 55, 6, 21, 35, 90, 91};
RemoveFactor5(data, sizeof(data)/sizeof(int));
main()
{
int data[]={12, 55, 6, 21, 35, 90, 91};
RemoveFactor5(data, sizeof(data)/sizeof(int));
(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 */
Example // MinMax.c
#include <stdio.h>
#include <limits.h>
#define MAX_NUM_ELEMENTS 50
main()
{
int data[MAX_NUM_ELEMENTS];
int i, count;
int min = INT_MAX, max = INT_MIN;
return count;
}
60
Example // MinMax.c
#include <stdio.h>
#include <limits.h>
#define MAX_NUM_ELEMENTS 50
main()
{
int data[MAX_NUM_ELEMENTS];
int i, count;
int min = INT_MAX, max = INT_MIN;
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
Binary Search
▪ 二元搜尋(binary search)
– 只能用在已排序的陣列
– 找出陣列的中間元素,將之與搜尋關鍵值作比較
- 如果相等的話,表示已找到要找的元素
- 如果關鍵值小於中間元素,就搜尋陣列的前半部
- 如果關鍵值大於中間元素,就搜尋陣列的後半部
- 重複
– 非常快速;最多 n 個步驟,其中 2n > 元素數量
- 30 個元素的陣列,至多五個步驟
25 > 30 ,因此至多五個步驟
67
Binary Search
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
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
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
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
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
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
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
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*
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.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
********
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
▪ 多維陣列
– 具有列(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;
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}};
#include <stdio.h>
printf(heading);
printf("\n");
}
108
printf(heading);
printf("\n");
}
109
#include <stdio.h>
printf(heading);
printf("\n");
}
110
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}};
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];
Example:
#define YEARS 5
#define TOTALSALES 10
#define PRODUCTS 5
int main(void)
{
int sales[YEARS][TOTALSALES][PRODUCTS];
int i, j, k;
HW #7
1. Write a C program which output an NN magic square,
where N is an odd integer. An NN 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