Introduction to C programming language (1) C Language 沒有多少句語法: (所以很簡單:) /* comment */ // comment too variable declaration/definition Assignment: var = expression; selection: if(expression) stat-1; else stat-2; switch(expr) { case-1: stat; ... } Loop control: for, while, do while for(exp1;exp2;exp3) statement; function definition / function call (2) C Language 設計者為了讓我們省下許多大家常做的事, 寫了很多 Library function 程式庫函數, 共有一百多個, 分為十五類, 它們的宣告被分到 15 個 .h 檔 (詳細請看 K&R 課本附錄 B) 與 Input/Output 有關: printf, scanf, fgetc, fopen, ... sqrt, sin, cos, ... 等數學函數 字串處理: strlen, strcpy, strcmp, strcat, ... isdigit(int), isspace(int), islower(int), toupper(int), ... 一些工具: atol, atof, malloc, free, rand, srand, qsort, ... 與時間有關: time(), clock( ), CLK_TCK, ... 一些#define 的符號常數: INT_MIN, INT_MAX, ULONG_MAX, ... 與實數有關的符號常數: FLT_MAX, DBL_MAX, ... ------ 其他較不常用: 可用來寫出不一定幾個參數的 function 與錯誤處理有關 (error handling ) signal 和 long jump, 與 Exception handling 有關 可生出程式診斷語句的巨集 Macro: assert(expression); 與在地化/國際化有關 不是給我們寫程式的人用的 :-) (3) 研究 之前說過 recursion 很好寫但是很慢! 例如 fibonacci's Rabbit problem: //第0個月有一對小兔子, 每月會長大, 大兔每月會生出一對, 請問第n月有幾對? long long fib(int n) { // recursive version, very SLOW ! if(n<0) return 0; if(n<2) return 1; return fib(n-1) + fib(n-2); //當 n > 50 你就會感覺很慢 } // fib // 如上的 Recursive version 很好寫, 但因會叫用很多次, 會很慢 ! 到底多慢? 可以用 裡面的 clock( ) 來量時間, 註: time(0) 只能量到秒 ! long long before, after, start, end, total; before = time(0); start = clock(); //... //... end = clock(); after = time(0); printf("CLK_TCK=%f\n", (double)CLK_TCK ); printf("CLOCKS_PER_SEC=%f\n", (double)CLOCKS_PER_SEC ); 詳細範例在: http://www.csie.nctu.edu.tw/~tsaiwn/introcs/OTHERS/clock/