Download presentation
Presentation is loading. Please wait.
Published byEugene Joseph Modified over 9 years ago
1
C Program Design C Arrays 主講人:虞台文
2
Content Basics Defining Arrays Array Initialization Static Arrays Passing Arrays to Functions Array Examples – Find Minimum and Maximum – Bubble Sort – Binary Search Strings and String Functions Multi-dimensional Arrays
3
C Program Design C Arrays Basics
4
陣列 (Arrays) Array is a data structure that stores contiguous data elements of the same type. Examples: intscore[50]; char address[50]; double distance[50]; score address distance 200 bytes 50 bytes 400 bytes
5
陣列 (Arrays) Examples: intscore[50]; char address[50]; double distance[50]; score address distance...... score[0] score[1] score[49]
6
陣列 (Arrays) score address distance address[0] address[1] address[2] address[49]...... Examples: intscore[50]; char address[50]; double distance[50];
7
陣列 (Arrays) score address distance...... distance[0] distance[49] Examples: intscore[50]; char address[50]; double distance[50];
8
陣列之使用 Examples: intscore[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 ]
9
陣列使用注意事項 陣列之索引 (index) 由 0 開始 – 一陣列若含 n 元素,其索引由 0 至 n-1 C Compiler 對陣列索引不做 out of range 檢查 – 易產生程式錯誤,甚或系統失敗 – 寫程式時程式設計師應保證陣列索引不超出範圍
10
C Program Design C Arrays Defining Arrays
11
arrayType arrayName[numberOfElements]; Examples: int c[10]; float myArray[3284]; int c[10]; float myArray[3284];
12
Defining Multiple Arrays of Same Type arrayType arrayName[numberOfElements]; Examples: int age[10], score[50]; double distance[50], average[100]; int age[10], score[50]; double distance[50], average[100];
13
C Program Design C Arrays Array Initialization
14
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}; 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};
15
範例: Initializers #include 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]); } #include 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]); }
16
範例: Initializers #include 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]); } #include 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]); } Debug Mode
17
範例: Initializers #include 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]); } #include 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]); } Release Mode 對未定義初值之陣列元素值勿做臆測
18
C Program Design C Arrays Static Arrays
19
Automatic Arrays #include 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]); } #include 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]); } Automatic arrays are created and, hence, initialized each time the corresponding function is called. Making arrays static “may” resolve the problem.
20
範例: 繪製一檔案中各字母(不區分 大小寫)出現頻率之直方圖 // histogram.c #include #define FALSE0 #define TRUE(!FALSE) #define HTG_SUBMIT_CHAR0 #define HTG_GET_CHAR_FREQ1 #define HTG_GET_TOTAL2 int histogram(int action, int c) { static int first = TRUE; // enter first time static int freq['z' - 'a' + 1], total=0; if(first){ // initialization needed int i; for(i = 0 ; i <'z'-'a' + 1; i++) freq[i]=0; first = FALSE; // initialized } switch(action){ case HTG_SUBMIT_CHAR: if(!isalpha(c)) return 0; total++; return ++freq[toupper(c) - 'A']; case HTG_GET_CHAR_FREQ: if(!isalpha(c)) return 0; return freq[toupper(c) - 'A']; default: return total; } // histogram.c #include <ctype.h> #define FALSE0 #define TRUE(!FALSE) #define HTG_SUBMIT_CHAR0 #define HTG_GET_CHAR_FREQ1 #define HTG_GET_TOTAL2 int histogram(int action, int c) { static int first = TRUE; // enter first time static int freq['z' - 'a' + 1], total=0; if(first){ // initialization needed int i; for(i = 0 ; i <'z'-'a' + 1; i++) freq[i]=0; first = FALSE; // initialized } switch(action){ case HTG_SUBMIT_CHAR: if(!isalpha(c)) return 0; total++; return ++freq[toupper(c) - 'A']; case HTG_GET_CHAR_FREQ: if(!isalpha(c)) return 0; return freq[toupper(c) - 'A']; default: return total; } } // histogram.h #define HTG_SUBMIT_CHAR0 #define HTG_GET_CHAR_FREQ1 #define HTG_GET_TOTAL2 int histogram(int action, int c); // histogram.h #define HTG_SUBMIT_CHAR0 #define HTG_GET_CHAR_FREQ1 #define HTG_GET_TOTAL2 int histogram(int action, int c);
21
範例: 繪製一檔案中各字母(不區分 大小寫)出現頻率之直方圖 // histogram.c #include #define FALSE0 #define TRUE(!FALSE) #define HTG_SUBMIT_CHAR0 #define HTG_GET_CHAR_FREQ1 #define HTG_GET_TOTAL2 int histogram(int action, int c) { static int first = TRUE; // enter first time static int freq['z' - 'a' + 1], total=0; if(first){ // initialization needed int i; for(i = 0 ; i <'z'-'a' + 1; i++) freq[i]=0; first = FALSE; // initialized } switch(action){ case HTG_SUBMIT_CHAR: if(!isalpha(c)) return 0; total++; return ++freq[toupper(c) - 'A']; case HTG_GET_CHAR_FREQ: if(!isalpha(c)) return 0; return freq[toupper(c) - 'A']; default: return total; } // histogram.c #include <ctype.h> #define FALSE0 #define TRUE(!FALSE) #define HTG_SUBMIT_CHAR0 #define HTG_GET_CHAR_FREQ1 #define HTG_GET_TOTAL2 int histogram(int action, int c) { static int first = TRUE; // enter first time static int freq['z' - 'a' + 1], total=0; if(first){ // initialization needed int i; for(i = 0 ; i <'z'-'a' + 1; i++) freq[i]=0; first = FALSE; // initialized } switch(action){ case HTG_SUBMIT_CHAR: if(!isalpha(c)) return 0; total++; return ++freq[toupper(c) - 'A']; case HTG_GET_CHAR_FREQ: if(!isalpha(c)) return 0; return freq[toupper(c) - 'A']; default: return total; } } // histogram.h #define HTG_SUBMIT_CHAR0 #define HTG_GET_CHAR_FREQ1 #define HTG_GET_TOTAL2 int histogram(int); // histogram.h #define HTG_SUBMIT_CHAR0 #define HTG_GET_CHAR_FREQ1 #define HTG_GET_TOTAL2 int histogram(int); How about if static is missing?
22
範例: 繪製一檔案中各字母(不區分 大小寫)出現頻率之直方圖 // main.c #include #include "histogram.h" main() { int c, total, i; do{ c = getchar(); histogram(HTG_SUBMIT_CHAR, c); } while(c != EOF); total = histogram(HTG_GET_TOTAL); if(total==0) return 0; for(i = 0; i < 26; i++){ int stars, j; printf("%c ", i+'A'); stars = 200.0 * histogram(HTG_GET_CHAR_FREQ, i+'A') / total; for(j=0; j<stars; j++) putchar('*'); putchar('\n'); } return 0; } // main.c #include #include "histogram.h" main() { int c, total, i; do{ c = getchar(); histogram(HTG_SUBMIT_CHAR, c); } while(c != EOF); total = histogram(HTG_GET_TOTAL); if(total==0) return 0; for(i = 0; i < 26; i++){ int stars, j; printf("%c ", i+'A'); stars = 200.0 * histogram(HTG_GET_CHAR_FREQ, i+'A') / total; for(j=0; j<stars; j++) putchar('*'); putchar('\n'); } return 0; } // histogram.h #define HTG_SUBMIT_CHAR0 #define HTG_GET_CHAR_FREQ1 #define HTG_GET_TOTAL2 int histogram(int action, int c); // histogram.h #define HTG_SUBMIT_CHAR0 #define HTG_GET_CHAR_FREQ1 #define HTG_GET_TOTAL2 int histogram(int action, int c);
23
範例: 繪製一檔案中各字母(不區分 大小寫)出現頻率之直方圖 // main.c #include #include "histogram.h" main() { int c, total, i; do{ c = getchar(); histogram(HTG_SUBMIT_CHAR, c); } while(c != EOF); total = histogram(HTG_GET_TOTAL); if(total==0) return 0; for(i = 0; i < 26; i++){ int stars, j; printf("%c ", i+'A'); stars = 200.0 * histogram(HTG_GET_CHAR_FREQ, i+'A') / total; for(j=0; j<stars; j++) putchar('*'); putchar('\n'); } return 0; } // main.c #include #include "histogram.h" main() { int c, total, i; do{ c = getchar(); histogram(HTG_SUBMIT_CHAR, c); } while(c != EOF); total = histogram(HTG_GET_TOTAL); if(total==0) return 0; for(i = 0; i < 26; i++){ int stars, j; printf("%c ", i+'A'); stars = 200.0 * histogram(HTG_GET_CHAR_FREQ, i+'A') / total; for(j=0; j<stars; j++) putchar('*'); putchar('\n'); } return 0; } // histogram.h #define HTG_SUBMIT_CHAR0 #define HTG_GET_CHAR_FREQ1 #define HTG_GET_TOTAL2 int histogram(int action, int c); // histogram.h #define HTG_SUBMIT_CHAR0 #define HTG_GET_CHAR_FREQ1 #define HTG_GET_TOTAL2 int histogram(int action, int c);
24
範例: 繪製一檔案中各字母(不區分 大小寫)出現頻率之直方圖 // main.c #include #include "histogram.h" main() { int c, total, i; do{ c = getchar(); histogram(HTG_SUBMIT_CHAR, c); } while(c != EOF); total = histogram(HTG_GET_TOTAL); if(total==0) return 0; for(i = 0; i < 26; i++){ int stars, j; printf("%c ", i+'A'); stars = 200.0 * histogram(HTG_GET_CHAR_FREQ, i+'A') / total; for(j=0; j<stars; j++) putchar('*'); putchar('\n'); } return 0; } // main.c #include #include "histogram.h" main() { int c, total, i; do{ c = getchar(); histogram(HTG_SUBMIT_CHAR, c); } while(c != EOF); total = histogram(HTG_GET_TOTAL); if(total==0) return 0; for(i = 0; i < 26; i++){ int stars, j; printf("%c ", i+'A'); stars = 200.0 * histogram(HTG_GET_CHAR_FREQ, i+'A') / total; for(j=0; j<stars; j++) putchar('*'); putchar('\n'); } return 0; } // histogram.h #define HTG_SUBMIT_CHAR0 #define HTG_GET_CHAR_FREQ1 #define HTG_GET_TOTAL2 int histogram(int action, int c); // histogram.h #define HTG_SUBMIT_CHAR0 #define HTG_GET_CHAR_FREQ1 #define HTG_GET_TOTAL2 int histogram(int action, int c);
25
範例: 繪製一檔案中各字母(不區分 大小寫)出現頻率之直方圖 // main.c #include #include "histogram.h" main() { int c, total, i; do{ c = getchar(); histogram(HTG_SUBMIT_CHAR, c); } while(c != EOF); total = histogram(HTG_GET_TOTAL); if(total==0) return 0; for(i = 0; i < 26; i++){ int stars, j; printf("%c ", i+'A'); stars = 200.0 * histogram(HTG_GET_CHAR_FREQ, i+'A') / total; for(j=0; j<stars; j++) putchar('*'); putchar('\n'); } return 0; } // main.c #include #include "histogram.h" main() { int c, total, i; do{ c = getchar(); histogram(HTG_SUBMIT_CHAR, c); } while(c != EOF); total = histogram(HTG_GET_TOTAL); if(total==0) return 0; for(i = 0; i < 26; i++){ int stars, j; printf("%c ", i+'A'); stars = 200.0 * histogram(HTG_GET_CHAR_FREQ, i+'A') / total; for(j=0; j<stars; j++) putchar('*'); putchar('\n'); } return 0; } // histogram.h #define HTG_SUBMIT_CHAR0 #define HTG_GET_CHAR_FREQ1 #define HTG_GET_TOTAL2 int histogram(int action, int c); // histogram.h #define HTG_SUBMIT_CHAR0 #define HTG_GET_CHAR_FREQ1 #define HTG_GET_TOTAL2 int histogram(int action, int c);
26
C Program Design C Arrays Passing Arrays to Functions
27
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
28
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.
29
Function Prototypes with Arrays void myFunction( int array[], int arraySize ); void myFunction( int[], int );
30
範例 #include 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) { 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; } #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) { 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; } 將一正整數陣 列中之各元素 移除因子 5
31
範例 #include 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) { 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; } #include 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) { 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; } 將一正整數陣 列中之各元素 移除因子 5
32
C Program Design C Arrays Array Examples
33
範例: // MinMax.c #include #define MAX_NUM_ELEMENTS50 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; } // MinMax.c #include <stdio.h> #include <limits.h> #define MAX_NUM_ELEMENTS50 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; } 搜尋最大值 與最小值
34
範例: // MinMax.c #include #define MAX_NUM_ELEMENTS50 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; } // MinMax.c #include <stdio.h> #include <limits.h> #define MAX_NUM_ELEMENTS50 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; } 搜尋最大值 與最小值
35
Bubble Sort
37
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; } 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; } } 範例 : Bubble Sort (I)
38
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; } 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; } void BubbleSort(int data[], int n) { int tmp, i, j, sorted; for(i=0, sorted=FALSE; !sorted && i<n-1; i++) for(j=0, sorted=TRUE; j<n-i-1; j++) if(data[j] > data[j+1]){ tmp = data[j]; data[j] = data[j+1]; data[j+1] = tmp; sorted = FALSE; } void BubbleSort(int data[], int n) { int tmp, i, j, sorted; for(i=0, sorted=FALSE; !sorted && i<n-1; i++) for(j=0, sorted=TRUE; j<n-i-1; j++) if(data[j] > data[j+1]){ tmp = data[j]; data[j] = data[j+1]; data[j+1] = tmp; sorted = FALSE; } 範例 : Bubble Sort (II)
39
Binary Search
40
int binSearch(int x, int v[], int n); 1 1 5 5 9 9 25 80 125 137 140 180 201 400 0 1 2 3 4 5 6 7 8 9 10 v[] binSearch(137, v, 11) binSearch(201, v, 11) binSearch(45, v, 11) 6 9 -1
41
Binary Search low = high = low <= high mid = (low + high) / 2 = 5 binSearch(25, v, 11) 1 1 5 5 9 9 25 80 125 137 140 180 201 400 0 1 2 3 4 5 6 7 8 9 10 v[] mid = v[mid] = 125 > 25
42
Binary Search low = binSearch(25, v, 11) 1 1 5 5 9 9 25 80 125 137 140 180 201 400 0 1 2 3 4 5 6 7 8 9 10 v[] mid = v[mid] = 125 > 25 high = high = mid - 1
43
Binary Search low = binSearch(25, v, 11) 1 1 5 5 9 9 25 80 125 137 140 180 201 400 0 1 2 3 4 5 6 7 8 9 10 v[] v[mid] = 9 < 25 high = low <= high mid = (low + high) / 2 = 2 mid =
44
Binary Search low = binSearch(25, v, 11) 1 1 5 5 9 9 25 80 125 137 140 180 201 400 0 1 2 3 4 5 6 7 8 9 10 v[] v[mid] = 9 < 25 high = mid = low = mid + 1
45
Binary Search low = binSearch(25, v, 11) 1 1 5 5 9 9 25 80 125 137 140 180 201 400 0 1 2 3 4 5 6 7 8 9 10 v[] high = mid = v[mid] = 25 == 25 low <= high mid = (low + high) / 2 = 3 3
46
Binary Search low = high = low <= high mid = (low + high) / 2 = 5 binSearch(45, v, 11) 1 1 5 5 9 9 25 80 125 137 140 180 201 400 0 1 2 3 4 5 6 7 8 9 10 v[] mid = v[mid] = 125 > 25
47
Binary Search low = binSearch(45, v, 11) 1 1 5 5 9 9 25 80 125 137 140 180 201 400 0 1 2 3 4 5 6 7 8 9 10 v[] mid = v[mid] = 125 > 45 high = high = mid - 1
48
Binary Search low = binSearch(45, v, 11) 1 1 5 5 9 9 25 80 125 137 140 180 201 400 0 1 2 3 4 5 6 7 8 9 10 v[] v[mid] = 9 < 45 high = low <= high mid = (low + high) / 2 = 2 mid =
49
Binary Search low = binSearch(45, v, 11) 1 1 5 5 9 9 25 80 125 137 140 180 201 400 0 1 2 3 4 5 6 7 8 9 10 v[] v[mid] = 9 < 45 high = mid = low = mid + 1
50
Binary Search low = binSearch(45, v, 11) 1 1 5 5 9 9 25 80 125 137 140 180 201 400 0 1 2 3 4 5 6 7 8 9 10 v[] high = mid = v[mid] = 25 < 45 low <= high mid = (low + high) / 2 = 3
51
Binary Search low= binSearch(45, v, 11) 1 1 5 5 9 9 25 80 125 137 140 180 201 400 0 1 2 3 4 5 6 7 8 9 10 v[] high = mid = v[mid] = 25 < 45 low = mid + 1
52
Binary Search low= binSearch(45, v, 11) 1 1 5 5 9 9 25 80 125 137 140 180 201 400 0 1 2 3 4 5 6 7 8 9 10 v[] high = mid = v[mid] = 80 > 45 low <= high mid = (low + high) / 2 = 4
53
Binary Search low= binSearch(45, v, 11) 1 1 5 5 9 9 25 80 125 137 140 180 201 400 0 1 2 3 4 5 6 7 8 9 10 v[] high = mid = v[mid] = 80 > 45 high = mid - 1
54
Binary Search low= binSearch(45, v, 11) 1 1 5 5 9 9 25 80 125 137 140 180 201 400 0 1 2 3 4 5 6 7 8 9 10 v[] high = mid = low <= high -1
55
範例 : 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 */ } /* 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 */ }
56
範例 : Binary Search
57
C Program Design C Arrays Strings and String Functions
58
Strings in C Null-terminated string In C, a string is a character array terminated with a ' \0 ' to mark the end. char str[]="hello\n"; Example: h (68) e (65) l (6C) o (6F) \n (0A) \0 (00) str str[0] str[1] str[2] str[3] str[4] str[5] str[6] sizeof(str) = 7 char str[]={'h', 'e', 'l', 'l', 'o', '\n', '\0'};
59
Reading Strings char string[BUF_SIZE]; // ensure buffer large enough scanf("%s", string); // not &string or scanf("%s", &string[0]); Reads characters until white character encountered. Be careful not to write past end of array, as it is possible to do so.
60
範例: Reading Strings #include main() { char string1[ 20 ]; /* reserves 20 characters */ char string2[] = "string literal"; /* reserves 15 characters */ int i; /* counter */ /* read string from user into array string1 */ printf( "Enter a string: " ); scanf( "%s", string1 ); /* input ended by whitespace character */ /* output string1 and string2 */ printf( "string1 is: %s\nstring2 is: %s\n", string1, string2 ); /* output space separated string for string1 */ printf( "string1 with spaces between characters is:\n" ); for ( i = 0; string1[ i ] != '\0'; i++ ) printf( "%c ", string1[ i ] ); printf( "\n" ); } #include main() { char string1[ 20 ]; /* reserves 20 characters */ char string2[] = "string literal"; /* reserves 15 characters */ int i; /* counter */ /* read string from user into array string1 */ printf( "Enter a string: " ); scanf( "%s", string1 ); /* input ended by whitespace character */ /* output string1 and string2 */ printf( "string1 is: %s\nstring2 is: %s\n", string1, string2 ); /* output space separated string for string1 */ printf( "string1 with spaces between characters is:\n" ); for ( i = 0; string1[ i ] != '\0'; i++ ) printf( "%c ", string1[ i ] ); printf( "\n" ); }
61
範例: Reading Strings #include main() { char string1[ 20 ]; /* reserves 20 characters */ char string2[] = "string literal"; /* reserves 15 characters */ int i; /* counter */ /* read string from user into array string1 */ printf( "Enter a string: " ); scanf( "%s", string1 ); /* input ended by whitespace character */ /* output string1 and string2 */ printf( "string1 is: %s\nstring2 is: %s\n", string1, string2 ); /* output space separated string for string1 */ printf( "string1 with spaces between characters is:\n" ); for ( i = 0; string1[ i ] != '\0'; i++ ) printf( "%c ", string1[ i ] ); printf( "\n" ); } #include main() { char string1[ 20 ]; /* reserves 20 characters */ char string2[] = "string literal"; /* reserves 15 characters */ int i; /* counter */ /* read string from user into array string1 */ printf( "Enter a string: " ); scanf( "%s", string1 ); /* input ended by whitespace character */ /* output string1 and string2 */ printf( "string1 is: %s\nstring2 is: %s\n", string1, string2 ); /* output space separated string for string1 */ printf( "string1 with spaces between characters is:\n" ); for ( i = 0; string1[ i ] != '\0'; i++ ) printf( "%c ", string1[ i ] ); printf( "\n" ); }
62
atoi and itoa int atoi( const char[] ); // ascii to integer int itoa( int, char[] ); // integer to ascii int atoi( const char[] ); // ascii to integer int itoa( int, char[] ); // integer to ascii
63
atoi int atoi( const char[] ); // ascii to integer int itoa( int, char[] ); // integer to ascii int atoi( const char[] ); // ascii to integer int itoa( int, char[] ); // integer to ascii char str[]="10759"; int val; val = atoi(str); str '1' '0' '7' '5' '9' '\0' val 10759 10 = 2A07 16 00 2A 07
64
atoi int atoi( const char[] ); // ascii to integer int itoa( int, char[] ); // integer to ascii int atoi( const char[] ); // ascii to integer int itoa( int, char[] ); // integer to ascii char str[]="10759"; int val; val = atoi(str); str '1' '0' '7' '5' '9' '\0' val 10759 10 = 2A07 16 00 2A 07 Byte order: Big-Endian & Little-Endian
65
itoa int atoi( const char[] ); // ascii to integer int itoa( int, char[] ); // integer to ascii int atoi( const char[] ); // ascii to integer int itoa( int, char[] ); // integer to ascii char str[6]; int val=10759; int len; len=itoa(val, str); str val 10759 10 = 2A07 16 00 2A 07 '1' '0' '7' '5' '9' '\0' // >> 5
66
範例 :atoi /* atoi: convert decimal string s to integer */ int atoi(const char s[]) { int i=0, val=0, sign; sign = s[i] == '-' ? -1 : 1; /* record sign */ if(s[i] == '+' || s[i] == '-') i++; /* skip sign if existent */ while(s[i] >= '0' && s[i] <= '9') /* non-numeric terminated */ val = 10 * val + (s[i++] - '0'); return val * sign; } /* atoi: convert decimal string s to integer */ int atoi(const char s[]) { int i=0, val=0, sign; sign = s[i] == '-' ? -1 : 1; /* record sign */ if(s[i] == '+' || s[i] == '-') i++; /* skip sign if existent */ while(s[i] >= '0' && s[i] <= '9') /* non-numeric terminated */ val = 10 * val + (s[i++] - '0'); return val * sign; }
67
範例 :itoa /* itoa: convert n to characters in s and return length */ int itoa(int n, char s[]) { int i, negative; n = (negative = (n < 0)) ? –n : n; /* record sign */ /* make n positive */ i = 0; do { /* generate digits in reverse order */ s[i++] = n % 10 + '0'; /* get next digit */ } while ((n /= 10) > 0); /* delete it */ if (negative) s[i++] = '-'; s[i] = '\0'; reverse(s); return i; } /* itoa: convert n to characters in s and return length */ int itoa(int n, char s[]) { int i, negative; n = (negative = (n < 0)) ? –n : n; /* record sign */ /* make n positive */ i = 0; do { /* generate digits in reverse order */ s[i++] = n % 10 + '0'; /* get next digit */ } while ((n /= 10) > 0); /* delete it */ if (negative) s[i++] = '-'; s[i] = '\0'; reverse(s); return i; }
68
範例 :strlen, reverse /* strlen: return the string length of s */ int strlen(const char s[]) { int i=0; while(s[i]) i++; return i; } /* reverse: reverse sting s */ void reverse(char s[]) { int i, j, temp; i = 0; j = strlen(s) - 1; while(i < j){ temp = s[i]; s[i] = s[j]; s[j] = temp; i++; j--; } /* strlen: return the string length of s */ int strlen(const char s[]) { int i=0; while(s[i]) i++; return i; } /* reverse: reverse sting s */ void reverse(char s[]) { int i, j, temp; i = 0; j = strlen(s) - 1; while(i < j){ temp = s[i]; s[i] = s[j]; s[j] = temp; i++; j--; } }
69
範例 :atoi (recurive version) // RecursiveAtoi.c // recursive_atoi: convert a decimal string (str) from index (start) // into an integer with heading value (val) int recursive_atoi(const char str[], int val, int start) { if(str[start] == '-') return -recursive_atoi(str, val, start+1); else if(str[start] == '+') return recursive_atoi(str, val, start+1); else if(str[start]=='\0') return val; else return recursive_atoi(str, val * 10 + (str[start] - '0'), start+1); } // atoi: convert a decimal string str into an integer // assume str is error free int atoi(const char str[]) { return recursive_atoi(str, 0, 0); } // RecursiveAtoi.c // recursive_atoi: convert a decimal string (str) from index (start) // into an integer with heading value (val) int recursive_atoi(const char str[], int val, int start) { if(str[start] == '-') return -recursive_atoi(str, val, start+1); else if(str[start] == '+') return recursive_atoi(str, val, start+1); else if(str[start]=='\0') return val; else return recursive_atoi(str, val * 10 + (str[start] - '0'), start+1); } // atoi: convert a decimal string str into an integer // assume str is error free int atoi(const char str[]) { return recursive_atoi(str, 0, 0); } start=3 '1''2''5''9''3''0''1''9''\0' str val=125
70
範例 :atoi (recurive version) // RecursiveAtoi.c // recursive_atoi: convert a decimal string (str) from index (start) // into an integer with heading value (val) int recursive_atoi(const char str[], int val, int start) { if(str[start] == '-') return -recursive_atoi(str, val, start+1); else if(str[start] == '+') return recursive_atoi(str, val, start+1); else if(str[start]=='\0') return val; else return recursive_atoi(str, val * 10 + (str[start] - '0'), start+1); } // atoi: convert a decimal string str into an integer // assume str is error free int atoi(const char str[]) { return recursive_atoi(str, 0, 0); } // RecursiveAtoi.c // recursive_atoi: convert a decimal string (str) from index (start) // into an integer with heading value (val) int recursive_atoi(const char str[], int val, int start) { if(str[start] == '-') return -recursive_atoi(str, val, start+1); else if(str[start] == '+') return recursive_atoi(str, val, start+1); else if(str[start]=='\0') return val; else return recursive_atoi(str, val * 10 + (str[start] - '0'), start+1); } // atoi: convert a decimal string str into an integer // assume str is error free int atoi(const char str[]) { return recursive_atoi(str, 0, 0); } start=0 '1''2''5''9''3''0''1''9''\0' str val=0
71
範例 :atoi (recurive version) // RecursiveAtoi.c // recursive_atoi: convert a decimal string (str) from index (start) // into an integer with heading value (val) int recursive_atoi(const char str[], int val, int start) { if(str[start] == '-') return -recursive_atoi(str, val, start+1); else if(str[start] == '+') return recursive_atoi(str, val, start+1); else if(str[start]=='\0') return val; else return recursive_atoi(str, val * 10 + (str[start] - '0'), start+1); } // atoi: convert a decimal string str into an integer // assume str is error free int atoi(const char str[]) { return recursive_atoi(str, 0, 0); } // RecursiveAtoi.c // recursive_atoi: convert a decimal string (str) from index (start) // into an integer with heading value (val) int recursive_atoi(const char str[], int val, int start) { if(str[start] == '-') return -recursive_atoi(str, val, start+1); else if(str[start] == '+') return recursive_atoi(str, val, start+1); else if(str[start]=='\0') return val; else return recursive_atoi(str, val * 10 + (str[start] - '0'), start+1); } // atoi: convert a decimal string str into an integer // assume str is error free int atoi(const char str[]) { return recursive_atoi(str, 0, 0); } start=8 '1''2''5''9''3''0''1''9''\0' str val=12593019 answer
72
範例 :atoi (recurive version) // RecursiveAtoi.c // recursive_atoi: convert a decimal string (str) from index (start) // into an integer with heading value (val) int recursive_atoi(const char str[], int val, int start) { if(str[start] == '-') return -recursive_atoi(str, val, start+1); else if(str[start] == '+') return recursive_atoi(str, val, start+1); if(str[start]=='\0') return val; else return recursive_atoi(str, val * 10 + (str[start] - '0'), start+1); } // atoi: convert a decimal string str into an integer // assume str is error free int atoi(const char str[]) { return recursive_atoi(str, 0, 0); } // RecursiveAtoi.c // recursive_atoi: convert a decimal string (str) from index (start) // into an integer with heading value (val) int recursive_atoi(const char str[], int val, int start) { if(str[start] == '-') return -recursive_atoi(str, val, start+1); else if(str[start] == '+') return recursive_atoi(str, val, start+1); if(str[start]=='\0') return val; else return recursive_atoi(str, val * 10 + (str[start] - '0'), start+1); } // atoi: convert a decimal string str into an integer // assume str is error free int atoi(const char str[]) { return recursive_atoi(str, 0, 0); }
73
範例 :atoi (recurive version) // RecursiveAtoi.c // recursive_atoi: convert a decimal string (str) from index (start) // into an integer with heading value (val) int recursive_atoi(const char str[], int val, int start) { if(str[start] == '-') return -recursive_atoi(str, val, start+1); else if(str[start] == '+') return recursive_atoi(str, val, start+1); else if(str[start]=='\0') return val; else return recursive_atoi(str, val * 10 + (str[start] - '0'), start+1); } // atoi: convert a decimal string str into an integer // assume str is error free int atoi(const char str[]) { return recursive_atoi(str, 0, 0); } // RecursiveAtoi.c // recursive_atoi: convert a decimal string (str) from index (start) // into an integer with heading value (val) int recursive_atoi(const char str[], int val, int start) { if(str[start] == '-') return -recursive_atoi(str, val, start+1); else if(str[start] == '+') return recursive_atoi(str, val, start+1); else if(str[start]=='\0') return val; else return recursive_atoi(str, val * 10 + (str[start] - '0'), start+1); } // atoi: convert a decimal string str into an integer // assume str is error free int atoi(const char str[]) { return recursive_atoi(str, 0, 0); }
74
範例 :atoi (recurive version) // RecursiveAtoi.c // recursive_atoi: convert a decimal string (str) from index (start) // into an integer with heading value (val) int recursive_atoi(const char str[], int val, int start) { if(str[start] == '-') return -recursive_atoi(str, val, start+1); else if(str[start] == '+') return recursive_atoi(str, val, start+1); else if(str[start]=='\0') return val; else return recursive_atoi(str, val * 10 + (str[start] - '0'), start+1); } // atoi: convert a decimal string str into an integer // assume str is error free int atoi(const char str[]) { return recursive_atoi(str, 0, 0); } // RecursiveAtoi.c // recursive_atoi: convert a decimal string (str) from index (start) // into an integer with heading value (val) int recursive_atoi(const char str[], int val, int start) { if(str[start] == '-') return -recursive_atoi(str, val, start+1); else if(str[start] == '+') return recursive_atoi(str, val, start+1); else if(str[start]=='\0') return val; else return recursive_atoi(str, val * 10 + (str[start] - '0'), start+1); } // atoi: convert a decimal string str into an integer // assume str is error free int atoi(const char str[]) { return recursive_atoi(str, 0, 0); } // main.c #include int atoi(char[]); main() { char str[20]; printf("Enter a numeric string:"); scanf("%s", str); printf("The value you type is:%d\n", atoi(str)); } // main.c #include int atoi(char[]); main() { char str[20]; printf("Enter a numeric string:"); scanf("%s", str); printf("The value you type is:%d\n", atoi(str)); }
75
範例 :itoa (recurive version) // RecursiveItoa.c // recursive_itoa: itoa 之輔助函式 // 將 n 值轉為十進制字串,將結果從 s 矩陣之 start 處開始擺放 // 傳回值為轉換後之字串長度 int recursive_itoa(int n, char s[], int start) { int len = 0; if(n/10) len = recursive_itoa(n/10, s, start); s[start+len] = n % 10 + '0'; return len+1; } // itoa: convert integer (n) into string (s) and return length int itoa(int n, char s[]) { int i=0; if(n<0){ s[i++]='-'; n = -n; } i += recursive_itoa(n, s, i); s[i]='\0'; return i; } // RecursiveItoa.c // recursive_itoa: itoa 之輔助函式 // 將 n 值轉為十進制字串,將結果從 s 矩陣之 start 處開始擺放 // 傳回值為轉換後之字串長度 int recursive_itoa(int n, char s[], int start) { int len = 0; if(n/10) len = recursive_itoa(n/10, s, start); s[start+len] = n % 10 + '0'; return len+1; } // itoa: convert integer (n) into string (s) and return length int itoa(int n, char s[]) { int i=0; if(n<0){ s[i++]='-'; n = -n; } i += recursive_itoa(n, s, i); s[i]='\0'; return i; } start xxxxxxxxx s
76
範例 :itoa (recurive version) // RecursiveItoa.c // recursive_itoa: itoa 之輔助函式 // 將 n 值轉為十進制字串,將結果從 s 矩陣之 start 處開始擺放 // 傳回值為轉換後之字串長度 int recursive_itoa(int n, char s[], int start) { int len = 0; if(n/10) len = recursive_itoa(n/10, s, start); s[start+len] = n % 10 + '0'; return len+1; } // itoa: convert integer (n) into string (s) and return length int itoa(int n, char s[]) { int i=0; if(n<0){ s[i++]='-'; n = -n; } i += recursive_itoa(n, s, i); s[i]='\0'; return i; } // RecursiveItoa.c // recursive_itoa: itoa 之輔助函式 // 將 n 值轉為十進制字串,將結果從 s 矩陣之 start 處開始擺放 // 傳回值為轉換後之字串長度 int recursive_itoa(int n, char s[], int start) { int len = 0; if(n/10) len = recursive_itoa(n/10, s, start); s[start+len] = n % 10 + '0'; return len+1; } // itoa: convert integer (n) into string (s) and return length int itoa(int n, char s[]) { int i=0; if(n<0){ s[i++]='-'; n = -n; } i += recursive_itoa(n, s, i); s[i]='\0'; return i; } start xxxxxxxxx sn=1024 ‘1’‘0’‘2’‘4’ Return 4
77
範例 :itoa (recurive version) // RecursiveItoa.c // recursive_itoa: itoa 之輔助函式 // 將 n 值轉為十進制字串,將結果從 s 矩陣之 start 處開始擺放 // 傳回值為轉換後之字串長度 int recursive_itoa(int n, char s[], int start) { int len = 0; if(n/10) len = recursive_itoa(n/10, s, start); s[start+len] = n % 10 + '0'; return len+1; } // itoa: convert integer (n) into string (s) and return length int itoa(int n, char s[]) { int i=0; if(n<0){ s[i++]='-'; n = -n; } i += recursive_itoa(n, s, i); s[i]='\0'; return i; } // RecursiveItoa.c // recursive_itoa: itoa 之輔助函式 // 將 n 值轉為十進制字串,將結果從 s 矩陣之 start 處開始擺放 // 傳回值為轉換後之字串長度 int recursive_itoa(int n, char s[], int start) { int len = 0; if(n/10) len = recursive_itoa(n/10, s, start); s[start+len] = n % 10 + '0'; return len+1; } // itoa: convert integer (n) into string (s) and return length int itoa(int n, char s[]) { int i=0; if(n<0){ s[i++]='-'; n = -n; } i += recursive_itoa(n, s, i); s[i]='\0'; return i; } start xxxxxxxxx s
78
範例 :itoa (recurive version) // RecursiveItoa.c // recursive_itoa: itoa 之輔助函式 // 將 n 值轉為十進制字串,將結果從 s 矩陣之 start 處開始擺放 // 傳回值為轉換後之字串長度 int recursive_itoa(int n, char s[], int start) { int len = 0; if(n/10) len = recursive_itoa(n/10, s, start); s[start+len] = n % 10 + '0'; return len+1; } // itoa: convert integer (n) into string (s) and return length int itoa(int n, char s[]) { int i=0; if(n<0){ s[i++]='-'; n = -n; } i += recursive_itoa(n, s, i); s[i]='\0'; return i; } // RecursiveItoa.c // recursive_itoa: itoa 之輔助函式 // 將 n 值轉為十進制字串,將結果從 s 矩陣之 start 處開始擺放 // 傳回值為轉換後之字串長度 int recursive_itoa(int n, char s[], int start) { int len = 0; if(n/10) len = recursive_itoa(n/10, s, start); s[start+len] = n % 10 + '0'; return len+1; } // itoa: convert integer (n) into string (s) and return length int itoa(int n, char s[]) { int i=0; if(n<0){ s[i++]='-'; n = -n; } i += recursive_itoa(n, s, i); s[i]='\0'; return i; }
79
String Functions
80
C Program Design C Arrays Multi-dimensional Arrays
81
Two-Dimensional Arrays A collection of a fixed number of components arranged in two dimensions – all components are of the same type – also called matrices Syntax: dataType arrayName[intexp1][intexp2]; where intexp1 and intexp2 are expressions yielding positive integer values
82
範例 : #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 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] ); } } //... }
83
2D-Arrays in Memory #define YEARS5 #define MONTHS12 float rainFall[YEARS][MONTHS]; rainFall[0][0] rainFall[0][1] rainFall[1][0] rainFall[1][1] rainFall[2][0] rainFall[2][1] rainFall[3][0] rainFall[3][1] rainFall[4][0] rainFall[4][1] rainFall[0][2] rainFall[1][2] rainFall[2][2] rainFall[3][2] rainFall[4][2]... rainFall[0][11]... rainFall[1][11]... rainFall[2][11]... rainFall[3][11]... rainFall[4][11] rainFall[0][0] rainFall[0][1] rainFall[0][2]... rainFall[0][11] rainFall[1][0] rainFall[1][1] rainFall[1][2]... rainFall[1][11] rainFall[2][0] rainFall[2][1] rainFall[2][2]... rainFall[2][11] rainFall[3][0] rainFall[3][1] rainFall[3][2]... rainFall[3][11] rainFall[4][0] rainFall[4][1] rainFall[4][2]... rainFall[4][11] Logical View Physical View rainFall[0] rainFall[1] rainFall[2] rainFall[3] rainFall[4] rainFall, rainFall[0] rainFall[1] rainFall[2] rainFall[3] rainFall[4] rainFall
84
2D-Arrays in Memory #define YEARS5 #define MONTHS12 float rainFall[YEARS][MONTHS]; rainFall[0][0] rainFall[0][1] rainFall[1][0] rainFall[1][1] rainFall[2][0] rainFall[2][1] rainFall[3][0] rainFall[3][1] rainFall[4][0] rainFall[4][1] rainFall[0][2] rainFall[1][2] rainFall[2][2] rainFall[3][2] rainFall[4][2]... rainFall[0][11]... rainFall[1][11]... rainFall[2][11]... rainFall[3][11]... rainFall[4][11] rainFall[0][0] rainFall[0][1] rainFall[0][2]... rainFall[0][11] rainFall[1][0] rainFall[1][1] rainFall[1][2]... rainFall[1][11] rainFall[2][0] rainFall[2][1] rainFall[2][2]... rainFall[2][11] rainFall[3][0] rainFall[3][1] rainFall[3][2]... rainFall[3][11] rainFall[4][0] rainFall[4][1] rainFall[4][2]... rainFall[4][11] Logical View Physical View rainFall[0] rainFall[1] rainFall[2] rainFall[3] rainFall[4] rainFall, rainFall[0] rainFall[1] rainFall[2] rainFall[3] rainFall[4] rainFall sizeof(rainFall)=? sizeof(rainFall[i])=?, i=0, …, 4 sizeof(rainFall[i][j])=?, i=0, …, 4, j=0, …, 11
85
2D-Arrays in Memory #define YEARS5 #define MONTHS12 float rainFall[YEARS][MONTHS]; rainFall[0][0] rainFall[0][1] rainFall[1][0] rainFall[1][1] rainFall[2][0] rainFall[2][1] rainFall[3][0] rainFall[3][1] rainFall[4][0] rainFall[4][1] rainFall[0][2] rainFall[1][2] rainFall[2][2] rainFall[3][2] rainFall[4][2]... rainFall[0][11]... rainFall[1][11]... rainFall[2][11]... rainFall[3][11]... rainFall[4][11] rainFall[0][0] rainFall[0][1] rainFall[0][2]... rainFall[0][11] rainFall[1][0] rainFall[1][1] rainFall[1][2]... rainFall[1][11] rainFall[2][0] rainFall[2][1] rainFall[2][2]... rainFall[2][11] rainFall[3][0] rainFall[3][1] rainFall[3][2]... rainFall[3][11] rainFall[4][0] rainFall[4][1] rainFall[4][2]... rainFall[4][11] Logical View Physical View rainFall[0] rainFall[1] rainFall[2] rainFall[3] rainFall[4] rainFall, rainFall[0] rainFall[1] rainFall[2] rainFall[3] rainFall[4] rainFall C compiler doesn’t perform out-of-bound checking. Accessing, e.g., rainFall[0][14] is not invalid.
86
2D-Arrays in Memory #define YEARS5 #define MONTHS12 float rainFall[YEARS][MONTHS]; rainFall[0][0] rainFall[0][1] rainFall[1][0] rainFall[1][1] rainFall[2][0] rainFall[2][1] rainFall[3][0] rainFall[3][1] rainFall[4][0] rainFall[4][1] rainFall[0][2] rainFall[1][2] rainFall[2][2] rainFall[3][2] rainFall[4][2]... rainFall[0][11]... rainFall[1][11]... rainFall[2][11]... rainFall[3][11]... rainFall[4][11] rainFall[0][0] rainFall[0][1] rainFall[0][2]... rainFall[0][11] rainFall[1][0] rainFall[1][1] rainFall[1][2]... rainFall[1][11] rainFall[2][0] rainFall[2][1] rainFall[2][2]... rainFall[2][11] rainFall[3][0] rainFall[3][1] rainFall[3][2]... rainFall[3][11] rainFall[4][0] rainFall[4][1] rainFall[4][2]... rainFall[4][11] Logical View Physical View rainFall[0] rainFall[1] rainFall[2] rainFall[3] rainFall[4] rainFall, rainFall[0] rainFall[1] rainFall[2] rainFall[3] rainFall[4] rainFall Can you figure out, though improper, the addresses of rainfall[5], rainfall[6], … ? How? MONTHS MONTHS 12
87
2D-Array Initialization #include 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)); } #include 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)); }
88
2D-Array as Function’s Argument #include 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"); } #include 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"); }
89
2D-Array as Function’s Argument #include 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"); } #include 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"); } Provide no information to the compiler for locating array ’s elements.
90
2D-Array as Function’s Argument #include 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"); } #include 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"); } void listElements(char heading[], int array[][3])
91
2D-Array as Function’s Argument #include void listElements(char heading[], int array[][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"); } #include void listElements(char heading[], int array[][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"); } #include 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}; 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) ); listElements("array1: ", array1); listElements("array2: ", array2); listElements("array3: ", array3); listElements("array4: ", array4); listElements("array5: ", array5); listElements("array6: ", array6); listElements("array7: ", array7); listElements("array8: ", array8); listElements("array9: ", array9); } #include 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}; 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) ); listElements("array1: ", array1); listElements("array2: ", array2); listElements("array3: ", array3); listElements("array4: ", array4); listElements("array5: ", array5); listElements("array6: ", array6); listElements("array7: ", array7); listElements("array8: ", array8); listElements("array9: ", array9); }
92
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
93
範例 : #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] ); } //... } #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] ); } //... }
94
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)
95
練習 : 1. Write a C program which output an N N magic square, where N is an odd integer. An N N magic square has N 2 cells that are filled with integers from 1 to N 2, and all of its column sums, row sums and the two diagonal sums have the same value. Reference:
96
練習 :Knight’s Tour 2. Problem 6.19 of the textbook 3. Problem 6.20 of the textbook
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.