C Program Design C Arrays 主講人:虞台文. Content Basics Defining Arrays Array Initialization Static Arrays Passing Arrays to Functions Array Examples – Find.

Slides:



Advertisements
Similar presentations
Lecture 20 Arrays and Strings
Advertisements

1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
Arrays. Introduction Arrays –Structures of related data items –Static entity - same size throughout program A few types –C-like, pointer-based arrays.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
資料結構實習-一 參數傳遞.
第六章 陣列.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays 6.3Declaring Arrays 6.4Examples Using Arrays 6.5Passing.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
Chapter 9: Arrays and Strings
Chapter 9: Arrays and Strings
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
Chapter 8 Arrays and Strings
 2007 Pearson Education, Inc. All rights reserved. 1 C Arrays.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Review: midterm #9 #include void main(void) { int c; c = getchar(); if(c>=48){ if(c
Systems Programming Concepts
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
 2006 Pearson Education, Inc. All rights reserved Arrays.
STRING Dong-Chul Kim BioMeCIS UTA 10/7/
Chapter 8 Arrays and Strings
C Program Design Functions and Program Structure 主講人:虞台文.
Chapter 6 Arrays Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Arrays CE 102 Algorithms and Programming KTO Karatay University Arrays are data structures consisting of data items of the same type Arrays are not dynamic.
Algorithm and Programming Array Dr. Ir. Riri Fitri Sari MM MSc International Class Electrical Engineering Dept University of Indonesia 15 March 2009.
ARRAY Prepared by MMD, Edited by MSY1.  Introduction to arrays  Declaring arrays  Initializing arrays  Examples using arrays  Relationship with pointers.
 2000 Prentice Hall, Inc. All rights reserved Arrays Array –Group of consecutive memory locations –Same name and type To refer to an element, specify.
Arrays Array –Group of consecutive memory locations –Same name and type To refer to an element, specify –Array name –Position number Format: arrayname.
C Lecture Notes 1 Arrays Lecture 6. C Lecture Notes 2 6.1Introduction Arrays –Structures of related data items –Static entity – same size throughout program.
chap8 Chapter 8 Arrays (reference: Deitel ’ s chap 6)
C Arrays Systems Programming. Systems Programming: Arrays 22 ArraysArrays  Arrays  Defining and Initializing Arrays  Array Example  Subscript Out-of-Range.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Pointers OVERVIEW.
Arrays  Array is a collection of same type elements under the same variable identifier referenced by index number.  Arrays are widely used within programming.
1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing Arrays to Functions 4.6Sorting Arrays 4.7Case.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Structured Programming Instructor: Prof. K. T. Tsang Lecture 6: Arrays 数据序列, 数组 1.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays.
Computer Programming for Engineers
Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers… –You need 7 variables (6 for winning numbers and 1 for the special number)
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Arrays Outline 6.1Introduction 6.2Arrays 6.3Declaring.
CHAPTER 3 ARRAYS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Arrays 3.Declaring Arrays 4.Examples Using Arrays 5.Multidimensional Arrays 6.Multidimensional.
CHAPTER 6 ARRAYS IN C 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 F. Alakeel.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
 2000 Prentice Hall, Inc. All rights reserved Arrays Array –Consecutive group of memory locations –Same name and type To refer to an element, specify.
KUKUM-06/07 EKT120: Computer Programming 1 Week 6 Arrays-Part 1.
1-d Arrays.
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Module 2 Arrays and strings – example programs.
C Arrays.
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
C Arrays.
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
Chapter 9 - Arrays Outline 6.1 Introduction 6.2 Arrays
EKT150 : Computer Programming
Arrays Outline Introduction Arrays Declaring Arrays
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
Your questions from last session
Arrays Arrays A few types Structures of related data items
Programming Language  C Control Flow
Presentation transcript:

C Program Design C Arrays 主講人:虞台文

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

C Program Design C Arrays Basics

陣列 (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

陣列 (Arrays) Examples: intscore[50]; char address[50]; double distance[50]; score address distance score[0] score[1] score[49]

陣列 (Arrays) score address distance address[0] address[1] address[2] address[49] Examples: intscore[50]; char address[50]; double distance[50];

陣列 (Arrays) score address distance distance[0] distance[49] Examples: intscore[50]; char address[50]; double distance[50];

陣列之使用 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[ ]  c[ 3 ]  c[ x ]

陣列使用注意事項 陣列之索引 (index) 由 0 開始 – 一陣列若含 n 元素,其索引由 0 至 n-1 C Compiler 對陣列索引不做 out of range 檢查 – 易產生程式錯誤,甚或系統失敗 – 寫程式時程式設計師應保證陣列索引不超出範圍

C Program Design C Arrays Defining Arrays

arrayType arrayName[numberOfElements]; Examples: int c[10]; float myArray[3284]; int c[10]; float myArray[3284];

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];

C Program Design C Arrays Array Initialization

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

範例: 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]); }

範例: 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

範例: 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 對未定義初值之陣列元素值勿做臆測

C Program Design C Arrays Static Arrays

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.

範例: 繪製一檔案中各字母(不區分 大小寫)出現頻率之直方圖 // 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);

範例: 繪製一檔案中各字母(不區分 大小寫)出現頻率之直方圖 // 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?

範例: 繪製一檔案中各字母(不區分 大小寫)出現頻率之直方圖 // 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 = * 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 = * 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);

範例: 繪製一檔案中各字母(不區分 大小寫)出現頻率之直方圖 // 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 = * 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 = * 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);

範例: 繪製一檔案中各字母(不區分 大小寫)出現頻率之直方圖 // 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 = * 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 = * 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);

範例: 繪製一檔案中各字母(不區分 大小寫)出現頻率之直方圖 // 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 = * 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 = * 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);

C Program Design C Arrays 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

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.

Function Prototypes with Arrays void myFunction( int array[], int arraySize ); void myFunction( int[], int );

範例 #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

範例 #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

C Program Design C Arrays Array Examples

範例: // 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; } 搜尋最大值 與最小值

範例: // 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; } 搜尋最大值 與最小值

Bubble Sort

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)

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)

Binary Search

int binSearch(int x, int v[], int n); v[] binSearch(137, v, 11) binSearch(201, v, 11) binSearch(45, v, 11) 6  9  -1 

Binary Search low = high = low <= high mid = (low + high) / 2 = 5 binSearch(25, v, 11) v[] mid = v[mid] = 125 > 25

Binary Search low = binSearch(25, v, 11) v[] mid = v[mid] = 125 > 25 high = high = mid - 1

Binary Search low = binSearch(25, v, 11) v[] v[mid] = 9 < 25 high = low <= high mid = (low + high) / 2 = 2 mid =

Binary Search low = binSearch(25, v, 11) v[] v[mid] = 9 < 25 high = mid = low = mid + 1

Binary Search low = binSearch(25, v, 11) v[] high = mid = v[mid] = 25 == 25 low <= high mid = (low + high) / 2 = 3 3 

Binary Search low = high = low <= high mid = (low + high) / 2 = 5 binSearch(45, v, 11) v[] mid = v[mid] = 125 > 25

Binary Search low = binSearch(45, v, 11) v[] mid = v[mid] = 125 > 45 high = high = mid - 1

Binary Search low = binSearch(45, v, 11) v[] v[mid] = 9 < 45 high = low <= high mid = (low + high) / 2 = 2 mid =

Binary Search low = binSearch(45, v, 11) v[] v[mid] = 9 < 45 high = mid = low = mid + 1

Binary Search low = binSearch(45, v, 11) v[] high = mid = v[mid] = 25 < 45 low <= high mid = (low + high) / 2 = 3

Binary Search low= binSearch(45, v, 11) v[] high = mid = v[mid] = 25 < 45 low = mid + 1

Binary Search low= binSearch(45, v, 11) v[] high = mid = v[mid] = 80 > 45 low <= high mid = (low + high) / 2 = 4

Binary Search low= binSearch(45, v, 11) v[] high = mid = v[mid] = 80 > 45 high = mid - 1

Binary Search low= binSearch(45, v, 11) v[] high = mid = low <= high  -1 

範例 : 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 */ }

範例 : Binary Search

C Program Design C Arrays Strings and String Functions

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

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.

範例: 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" ); }

範例: 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" ); }

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

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 = 2A A 07

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 = 2A A 07 Byte order: Big-Endian & Little-Endian

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 = 2A A 07 '1' '0' '7' '5' '9' '\0' // >> 5

範例 :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; }

範例 :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; }

範例 :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--; } }

範例 :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

範例 :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

範例 :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=  answer

範例 :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); }

範例 :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); }

範例 :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)); }

範例 :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

範例 :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

範例 :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

範例 :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; }

String Functions

C Program Design C Arrays Multi-dimensional Arrays

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

範例 : #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] ); } } //... }

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

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

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.

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

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

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"); }

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.

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])

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

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

範例 : #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] ); } //... }

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)

練習 : 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:

練習 :Knight’s Tour 2. Problem 6.19 of the textbook 3. Problem 6.20 of the textbook