{"cells":[{"cell_type":"markdown","metadata":{"id":"9xoK4OIjIfZA"},"source":["# 第三週上課內容"]},{"cell_type":"markdown","metadata":{"id":"05G1Fqg6GRZX"},"source":["###GitHub 教材參考資料\n","\n","* String\n","  * https://github.com/htchen/i2p-nthu/blob/master/程式設計一/Printf%20and%20Scanf/String%20type.md\n","\n","* Operators, Expressions, and Statements\n","  * https://github.com/htchen/i2p-nthu/tree/master/程式設計一/Operators%2C%20Expressions%2C%20and%20Statements\n","\n","* Looping\n","  * https://github.com/htchen/i2p-nthu/tree/master/程式設計一/Looping"]},{"cell_type":"markdown","metadata":{"id":"PgtHuoX5YIz6"},"source":["### Example 1\n","我們來看看 E03_01.c 這個程式做了哪些事情以及用到了哪些新的東西。"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":5,"status":"ok","timestamp":1646137248038,"user":{"displayName":"HT Chen","photoUrl":"https://lh3.googleusercontent.com/a/default-user=s64","userId":"17748361917871513601"},"user_tz":-480},"id":"vh5utIm1dKHz","outputId":"615e4080-3903-439a-9795-42fac59315d3"},"outputs":[{"name":"stdout","output_type":"stream","text":["Overwriting E03_01.c\n"]}],"source":["%%writefile E03_01.c\n","#include <stdio.h>\n","#include <string.h>\n","#define SPEED 0.083\n","\n","int main(void)\n","{\n","   float minutes, distance; // float 4 bytes = 32 bits, double 8 bytes = 64 bits\n","   int size, letters, my_letters;  // 4 bytes = 32 bits  -2147483248 ~ +2147483247\n","   char name[10]; /* character array, string      array: 陣列 */\n","   int i;\n"," \n","   /*\n","   [name]\n","   0x1000  0x1001  0x1002  0x1003  0x1004  0x1005  0x1006  0x1007  0x1008  0x1009\n","   'S'     't'     'e'     '0'     'e'     '\\0'    'd'     'd'     'w'     'e'    \n","   */\n"," \n","   printf(\"Hi! What's your first name? \");\n","   scanf(\"%9s\", name);\n","   printf(\"\\n%s, how many minutes does it take to walk from\\n\", name);\n","   printf(\"your dormitory to the Delta building? \");\n","   scanf(\"%f\", &minutes);\n","   size = sizeof(name);\n","   letters = strlen(name);\n","\n","   distance = minutes * SPEED;  \n","   printf(\"\\nThe distance from your dormitory to the Delta building\\n\");\n","   printf(\"is about %.3f kilometers.\\n\\n\", distance);\n","  \n","   printf(\"By the way, your first name has %d letters,\\n\", letters);\n","   printf(\"and we have %d bytes to store it in.\\n\", size);\n","  \n","   return 0;\n","}"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":10334,"status":"ok","timestamp":1646137262134,"user":{"displayName":"HT Chen","photoUrl":"https://lh3.googleusercontent.com/a/default-user=s64","userId":"17748361917871513601"},"user_tz":-480},"id":"Ug0ozLfLdpNi","outputId":"25ca3a1e-4c01-40f8-d15f-5ec36d116b23"},"outputs":[{"name":"stdout","output_type":"stream","text":["Hi! What's your first name? St0ve\n","\n","St0ve, how many minutes does it take to walk from\n","your dormitory to the Delta building? 8\n","83 116 48 118 101 0\n","S t 0 v e \u0000\n","\n","The distance from your dormitory to the Delta building\n","is about 0.664 kilometers.\n","\n","By the way, your first name has 5 letters,\n","and we have 10 bytes to store it in.\n"]},{"data":{"text/plain":[""]},"execution_count":49,"metadata":{},"output_type":"execute_result"}],"source":["%%shell\n","\n","gcc E03_01.c -o E03_01\n","./E03_01"]},{"cell_type":"markdown","metadata":{"id":"VKYGPmbvE57_"},"source":["\n","執行 E03_01 這個程式會得到類似下面的結果:\n","```\n","Hi! What's your first name? Stevie\n","\n","Stevie, how many minutes does it take to walk from your dormitory to the CS building? 8\n","\n","The distance from your dormitory to the CS building is about 0.664 kilometers.\n","       \n","By the way, your first name has 6 letters, and we have 10 bytes to store it in.\n","```\n","程式先用 `printf()` 顯示訊息，詢問使用者的名字，然後用 `scanf()` 來讀取使用者輸入的 \"字串\"，把字串儲存在變數 `name` 裡面。再來就可以用儲存起來的字串稱呼使用者，並且問一個簡單的問題，再把計算結果顯示在螢幕上。程 式裡面用到的新東西首先是 `#include <string.h>`。回想當初程式需要 `#include <stdio.h>` 是因為要用到 `printf()`，同樣地，引入 `string.h` 是為了要用到其中相關的 function，在這個例子用到的是 `strlen()` 這個 function，它可以計算字串變數裡面所儲存的字串的長度。傳入的參數是字串，傳回的整數值就是字串長度，以 `Stevie` 為例，長度是 `6`。程式第三行的 `#define SPEED 0.083` 利用 C Preprocessor 來做前處理，在 compile 之 前，會先把程式裡所有出現的 `SPEED` 字眼通通取代成 `0.083`。字串其實是靠所謂的 character array 來儲存。當我們宣告\n","`char name[10];`\n","表示 name 會佔用到十個 bytes 的記憶體，等於是有十個空位，每個空位的大小是一個 byte，每個 byte 的空間可以 存放一個字元。接下來會看到 `printf()` 和 `scanf()` 裡都用到 `%s`，表示要處理的輸入輸出資料是字串 (string)。有一個比較特別的地方是在 `scanf()` 裡 `weight` 前面有加 `&`，但是 `name` 前面卻沒有。(由此可以推測 `&weight` 和 `name` 應該代表著對等的性質。稍後我們就會解釋，其實它們都對應到記憶體位址。)\n","  \n","**字元陣列 character arrays 與字串**\n","\n","`S t e v i e \\0`\n","\n","字串裡的字元必須連續地存放在記憶體中，所以剛好可以用陣列來儲存，因為陣列就是一連串的記憶體空間。字元陣 列的每一格空間可以存放一個字元 (`char`)，當我們宣告 `char name[10];` 表示要保留十格空間存放十個字元，每一格可以容納一個 `char` 型別的資料。當然除了 `char` 之外，也可用其他型別如 `int` 來宣告陣列，目前我們先專心探討字元陣列。為了標記整個字串究竟在哪裡算是結尾，C 語言使用一個特殊的字元 `'\\0'` 來表示字串結尾。字元 `'\\0'` 對 應到的 ASCII 值是 `0`。我們也可以用整數 `0` 來代替字元 `'\\0'`，但為了有所區別，當字元使用時最好寫成 `'\\0'`。\n","\n","宣告陣列產生一個可以容納十個字元的 array，準備用來記錄使用者輸入的字串 (使用者的名字)。因為要保留一格給 '\\0' 字元來標示字串結尾，所以其實真正能用來記錄的人名長度，最多只能包含九個字元。如何把字串存入陣列中呢? 在前面的例子裡用的方法是 `scanf(\"%s\", name);` 讀取使用者輸入的字串。所以 `%s` 就表示要把使用者輸入的東西當作 \"字串\" 讀進來，然後參數 `name` 就是要存放字串的陣列名稱，這個名稱所代表的意義是整個字串的開頭位址。因此 `scanf()` 就能由 `name` 找到陣列開頭位址，一格一格把字元填進去，而且會自動在最後加上 `'\\0'` 當作結束。"]},{"cell_type":"markdown","metadata":{"id":"jUOvUxUPYlH1"},"source":["##Example 2\n","###More on `printf()` and `scanf()`"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":426,"status":"ok","timestamp":1646139131099,"user":{"displayName":"HT Chen","photoUrl":"https://lh3.googleusercontent.com/a/default-user=s64","userId":"17748361917871513601"},"user_tz":-480},"id":"p_T8eu3Wkk4k","outputId":"5563a746-f9ba-4fa8-93bb-620380d8c4dd"},"outputs":[{"name":"stdout","output_type":"stream","text":["Overwriting E03_02.c\n"]}],"source":["%%writefile E03_02.c\n","\n","#include <stdio.h>\n","#define ENGINE 1499.99\n","\n","void test_float(void)\n","{\n","   printf(\"~%f~\\n\", ENGINE);\n","   printf(\"~%e~\\n\", ENGINE);\n","   printf(\"~%4.2f~\\n\", ENGINE);\n","   printf(\"~%3.1f~\\n\", ENGINE);\n","   printf(\"~%10.3f~\\n\", ENGINE);\n","   printf(\"~%-10.3f~\\n\", ENGINE);\n","   printf(\"~%12.3e~\\n\", ENGINE);\n","   printf(\"~%+4.2f~\\n\", ENGINE);\n","   printf(\"~%010.2f~\\n\", ENGINE);\n","}\n","\n","void test_precision(void)\n","{\n","    int width, precision;\n","    double rate = 123.45;\n","    printf(\"Enter a width and a precision: \");\n","    scanf(\"%d%d\", &width, &precision);\n","    printf(\"rate: '%*.*f'\\n\", width, precision, rate);\n","}\n","}\n","int main(void)\n","{\n","  test_float();\n","  test_precision();\n","   return 0;\n","}"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":415},"executionInfo":{"elapsed":30,"status":"error","timestamp":1646138078296,"user":{"displayName":"HT Chen","photoUrl":"https://lh3.googleusercontent.com/a/default-user=s64","userId":"17748361917871513601"},"user_tz":-480},"id":"lWuINPf0lIUE","outputId":"9f7ca533-60f1-4ae4-fe61-5db73109d2f5"},"outputs":[{"name":"stdout","output_type":"stream","text":["\u001b[01m\u001b[KE03_02.c:26:1:\u001b[m\u001b[K \u001b[01;31m\u001b[Kerror: \u001b[m\u001b[Kexpected identifier or ‘\u001b[01m\u001b[K(\u001b[m\u001b[K’ before ‘\u001b[01m\u001b[K}\u001b[m\u001b[K’ token\n"," \u001b[01;31m\u001b[K}\u001b[m\u001b[K\n"," \u001b[01;31m\u001b[K^\u001b[m\u001b[K\n","/bin/bash: line 2: ./E03_02: No such file or directory\n"]},{"ename":"CalledProcessError","evalue":"ignored","output_type":"error","traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mCalledProcessError\u001b[0m                        Traceback (most recent call last)","\u001b[0;32m<ipython-input-51-9ac5ad770acb>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mget_ipython\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mrun_cell_magic\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'shell'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m''\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'\\ngcc E03_02.c -o E03_02\\n./E03_02'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m","\u001b[0;32m/usr/local/lib/python3.7/dist-packages/IPython/core/interactiveshell.py\u001b[0m in \u001b[0;36mrun_cell_magic\u001b[0;34m(self, magic_name, line, cell)\u001b[0m\n\u001b[1;32m   2115\u001b[0m             \u001b[0mmagic_arg_s\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mvar_expand\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mline\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mstack_depth\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   2116\u001b[0m             \u001b[0;32mwith\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mbuiltin_trap\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 2117\u001b[0;31m                 \u001b[0mresult\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mfn\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mmagic_arg_s\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mcell\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m   2118\u001b[0m             \u001b[0;32mreturn\u001b[0m \u001b[0mresult\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   2119\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n","\u001b[0;32m/usr/local/lib/python3.7/dist-packages/google/colab/_system_commands.py\u001b[0m in \u001b[0;36m_shell_cell_magic\u001b[0;34m(args, cmd)\u001b[0m\n\u001b[1;32m    111\u001b[0m   \u001b[0mresult\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0m_run_command\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcmd\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mclear_streamed_output\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mFalse\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    112\u001b[0m   \u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0mparsed_args\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mignore_errors\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 113\u001b[0;31m     \u001b[0mresult\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcheck_returncode\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m    114\u001b[0m   \u001b[0;32mreturn\u001b[0m \u001b[0mresult\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    115\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n","\u001b[0;32m/usr/local/lib/python3.7/dist-packages/google/colab/_system_commands.py\u001b[0m in \u001b[0;36mcheck_returncode\u001b[0;34m(self)\u001b[0m\n\u001b[1;32m    137\u001b[0m     \u001b[0;32mif\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mreturncode\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    138\u001b[0m       raise subprocess.CalledProcessError(\n\u001b[0;32m--> 139\u001b[0;31m           returncode=self.returncode, cmd=self.args, output=self.output)\n\u001b[0m\u001b[1;32m    140\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    141\u001b[0m   \u001b[0;32mdef\u001b[0m \u001b[0m_repr_pretty_\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mp\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mcycle\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m  \u001b[0;31m# pylint:disable=unused-argument\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n","\u001b[0;31mCalledProcessError\u001b[0m: Command '\ngcc E03_02.c -o E03_02\n./E03_02' returned non-zero exit status 127."]}],"source":["%%shell\n","\n","gcc E03_02.c -o E03_02\n","./E03_02"]},{"cell_type":"markdown","metadata":{"id":"P5fyufV1aPlg"},"source":["第一部分的輸出結果如下：\n","```\n","~1499.990000~\n","~1.499990e+003~\n","~1499.99~\n","~1500.0~\n","~  1499.990~\n","~1499.990  ~\n","~  1.500e+003~\n","~+1499.99~\n","~0001499.99~\n","```\n","\n","從輸出結果可以猜出每種格式的功用。第三個 `printf()`，`%4.2f` 表示最少要顯示出四個字元寬度，而小數點後要顯示二位小數。第四個 `printf()` 用的是 `%3.1f`，所以最少要顯示出三個字元寬，而小數點後只顯示一位小數，這麼做會使得原本的數字被自動四捨五入。第五個 `printf()` 因為用了 `%10.3f` 所以最少要顯示十個字元寬 (不足的會補空白)，然後小數點後顯示三位小數; 可以數數看在兩個 `~` 符號中間是否正好包含十個字元 (包含空白字元和小數點)。接下來 `%-10.3f` 意思和 `%10.3f` 相同，差別只是變成要向左靠齊 (這是加了 `–` 號的效果)。第七個 `printf()` 用的是 `%12.3e` 所以總寬度是 12 個字元，一樣可以數數看是否有 12 個字元，不足的也會用空白來填補。而由於小數點後只顯示三位小數，所以無法完整表示成 `1.49999e+003`，會被自動四捨五入成 `1.500e+003`。第八個 `printf()` 用 `%+4.2f` 多了 `+` 號只是表示要在數字前面顯示正負號，因為 `1499.99` 是個正數，所以就多顯示了 `+` 號。最後一個 `printf()` 用到 `%010.2f` 意思是要顯示最少十個字元寬，不足個地方不再是用空白來補，而是改成補零。以上這些就是可能會用到的格式設定。"]},{"cell_type":"markdown","metadata":{"id":"pIZQfRrxI9dk"},"source":["##Example 3\n","###Using the `%*.s` format in `printf()`"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":9,"status":"ok","timestamp":1646140069324,"user":{"displayName":"HT Chen","photoUrl":"https://lh3.googleusercontent.com/a/default-user=s64","userId":"17748361917871513601"},"user_tz":-480},"id":"B1PwthGooDPC","outputId":"fd349866-f8f2-4a6a-e7bc-e4e706b944c2"},"outputs":[{"name":"stdout","output_type":"stream","text":["Overwriting E03_03.c\n"]}],"source":["%%writefile E03_03.c\n","\n","#include <stdio.h>\n","#include <string.h>\n","#define BORDER \"############################################\"\n","int main(void)\n","{\n","    char word[26];\n","    scanf(\"%25s\", word);\n","    printf(\"%.*s\\n\", (int)strlen(word)+2, BORDER);\n","    printf(\"#%s#\\n\", word);    \n","    printf(\"%.*s\\n\", (int)strlen(word)+2, BORDER);\n"," \n","    return 0 ;\n","}\n","/*\n","Input: University\n","############\n","#University#\n","############\n","*/"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":8973,"status":"ok","timestamp":1646140082820,"user":{"displayName":"HT Chen","photoUrl":"https://lh3.googleusercontent.com/a/default-user=s64","userId":"17748361917871513601"},"user_tz":-480},"id":"whPuzHv0oMQe","outputId":"e72e5a0d-213b-42db-cab1-dea7edb55d93"},"outputs":[{"name":"stdout","output_type":"stream","text":["University\n","############\n","#University#\n","############\n","Mar  1 2022\n","13\n","main\n"]},{"data":{"text/plain":[""]},"execution_count":60,"metadata":{},"output_type":"execute_result"}],"source":["%%shell\n","\n","gcc E03_03.c -o E03_03\n","./E03_03"]},{"cell_type":"markdown","metadata":{"id":"7xX5Z3SybcyS"},"source":["**用 `printf()` 輸出字串時的格式設定**\n","各種用法的整理:\n","1. 如果寫\n","`printf(\"%.3s\\n\", \"university\");` 會輸出 `uni` 也就是只會輸出前三個字元\n","2. 如果寫\n","`printf(\"%15s\\n\", \"university\");` 會輸出 `university` 前面會多五個空格\n","3. 如果寫\n","`printf(\"%15.3s\\n\", \"university\");`\n","則會輸出 `uni` 也就輸出 `university` 的前三個字元 然後前面會多加入 12 個空格 總共長度是 15 個字元\n","\n","`printf(\"%*.*s\\n\", 15, 3, \"university\");`\n","\n","4. 如果寫\n","`printf(\"%*.*s\\n\", 15, 3, \"university\");`\n","則是用動態的方式來設定格式 在這個例子得到的輸出結果也是 `uni` 也就是把兩個 `*` 號分別用 15 和 3 取代 相當於 `\"%15.3s\\n\"` 的效果"]},{"cell_type":"markdown","metadata":{"id":"BRqiWY7TnSdc"},"source":["###C preprocessor\n","```\n","#define\n","#include\n","```\n","Predefined macros\n","```\n","__FILE__\n","__LINE__\n","__func__\n","__DATE__\n","__TIME__\n","```"]},{"cell_type":"markdown","metadata":{"id":"B-lLbFgDcRzz"},"source":["###Floating point representations\n","\n","The details of floating point representations that I cannot explain clearly in the class are available at \n","\n","http://en.wikipedia.org/wiki/Floating_point\n","\n","and\n","\n","http://en.wikipedia.org/wiki/C99#IEEE_754_floating_point_support\n"]},{"cell_type":"markdown","metadata":{"id":"rBmybqFEgdeY"},"source":["##Example 4\n","###`while` loop"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":427,"status":"ok","timestamp":1646140636503,"user":{"displayName":"HT Chen","photoUrl":"https://lh3.googleusercontent.com/a/default-user=s64","userId":"17748361917871513601"},"user_tz":-480},"id":"a5FKAEdupAO0","outputId":"5ea2f6f4-594f-41bb-ed28-b80a91b4efa3"},"outputs":[{"name":"stdout","output_type":"stream","text":["Overwriting E03_04.c\n"]}],"source":["%%writefile E03_04.c\n","\n","#include <stdio.h>\n","int main(void)\n","{\n","    int x, n;\n","    int i, sum;\n","    int a[50];\n","\n","    printf(\"How many numbers? (n<50) \");\n","\n","    scanf(\"%d\", &n);\n","    i = 0;\n","    while (i < n) {\n","        printf(\"Input a[%d]: \", i);\n","        scanf(\"%d\", &x);\n","\n","        printf(\"The number is %d\\n\", x);\n","\n","        a[i] = x;\n","\n","        i = i + 1;\n","    }\n","    i = 0;\n","\n","    sum = 0;\n","\n","    while (i < n) {\n","        printf(\"%d + \", a[i]);\n","        sum = sum + a[i];\n","        i++; \n","    }\n","    printf(\"\\b\\b= %d\\n\", sum);\n","    return 0;\n","}"]},{"cell_type":"markdown","metadata":{"id":"e7SrHJCZg9Uh"},"source":["輸入下面資料來做測試\n","```\n","How many numbers? (n<50) 5\n","Input a[0]: 10\n","The number is 10\n","Input a[1]: 20\n","The number is 20\n","Input a[2]: 30\n","The number is 30\n","Input a[3]: 40\n","The number is 40\n","Input a[4]: 50\n","The number is 50\n","10 + 20 + 30 + 40 + 50 = 150\n","```"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":10300,"status":"ok","timestamp":1646140650998,"user":{"displayName":"HT Chen","photoUrl":"https://lh3.googleusercontent.com/a/default-user=s64","userId":"17748361917871513601"},"user_tz":-480},"id":"JKQybP6upHEm","outputId":"e9ff28be-3f8a-45a9-8246-d003ac09056e"},"outputs":[{"name":"stdout","output_type":"stream","text":["How many numbers? (n<50) 3\n","Input a[0]: 7\n","The number is 7\n","Input a[1]: 8\n","The number is 8\n","Input a[2]: 9\n","The number is 9\n","7 + 8 + 9 + \b\b= 24\n"]},{"data":{"text/plain":[""]},"execution_count":68,"metadata":{},"output_type":"execute_result"}],"source":["%%shell\n","\n","gcc E03_04.c -o E03_04\n","./E03_04"]},{"cell_type":"markdown","metadata":{"id":"RvAsriUCpeCI"},"source":["##Example 5"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":441,"status":"ok","timestamp":1646140798351,"user":{"displayName":"HT Chen","photoUrl":"https://lh3.googleusercontent.com/a/default-user=s64","userId":"17748361917871513601"},"user_tz":-480},"id":"mGsLcKRnpXVd","outputId":"4454feb3-6575-40e3-b76a-974c9e7fce64"},"outputs":[{"name":"stdout","output_type":"stream","text":["Writing E03_05.c\n"]}],"source":["%%writefile E03_05.c\n","\n","#include <stdio.h>\n","#define STEP 10\n","#define LOWER 0\n","#define UPPER 100\n","int main(void)\n","{\n","    int fahr, celsius;\n","\n","    printf(\"Celsius    Fahrenheit\\n\");\n","\n","    printf(\"---------------------\\n\");\n","    celsius = LOWER;\n","\n","    while (celsius <= UPPER) {\n","\n","        fahr = 1.8*celsius + 32;\n","\n","        printf(\"%4d %12d\\n\", celsius, fahr);\n","\n","        celsius = celsius + STEP;\n","    }\n","    printf(\"---------------------\\n\");\n","\n","    return 0;\n","}"]},{"cell_type":"markdown","metadata":{"id":"Hh3ZNuwyhicd"},"source":["這個程式會列出攝氏和華氏溫度的對照表，範圍從攝氏零度到一百度。程式用到了 `while` 迴圈來達到反覆呼叫\n","`printf()` 的效果。當程式執行到 `while` 時，會先檢查括號裡的式子: `(celsius <= UPPER)`\n","這個式子是在判斷 `celsius` 是否小於 `UPPER`，由於在執行到 `while` 之前的一行，`celsius` 的值被設為 `LOWER` (值為 0)， 所以目前 `celsius` 的確小於 `UPPER`。由於 `celsius` 與 `UPPER` 的實際大小關係符合這個式子所描述，所以這個式子會得到 `true`，表示這個式子是成立的，因此程式就可繼續執行 `while` 迴圈接下來的敘述。整個 `while` 迴圈的內容被包 含在 `{ }` 所定義的有效範圍內。接下來要執行的程式碼就是\n","\n","`fahr = 1.8*celsius + 32;` \n","\n","`printf(\"%4d %12d\\n\", celsius, fahr);`\n","\n","代入換算公式，再把對照值有固定格式印出來。接下來 `ceisius` 的值會被累加上 `STEP`\n"," \n","`celsius = celsius + STEP;`\n","\n","這一行的意思就是把 `celsius` 加上 `STEP` 之後，得到的值再存回 `celsius`。所以 `celsius` 的值從 `0` 變成 `10`，然後程式的進行會回到 `while` 的判斷式，再次判斷 `celsius <= UPPER` 是否成立。這樣一直反覆進行下去，不斷地在螢幕上印出攝氏華氏對照值，而且 `celsius` 的值也會不斷增加。一直到 `celsius` 的值變成 `100`，然後再經過 `celsius = celsius + STEP;` 之後變成 `110`，這時候回到判斷式 `celsius <= UPPER` 就會發現條件不成立，因為 `110` 已經比 `100` 大，所以 `while` 迴圈就此結束，程式接下來直接跳到 `while { ... }` 之外，執行下一行程式碼 `printf(\"---------------------\\n\");`\n"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":410,"status":"ok","timestamp":1646140804057,"user":{"displayName":"HT Chen","photoUrl":"https://lh3.googleusercontent.com/a/default-user=s64","userId":"17748361917871513601"},"user_tz":-480},"id":"RK7kVd2wq3ln","outputId":"abaa07ea-87ee-4e9d-b851-efaf21faf1e5"},"outputs":[{"name":"stdout","output_type":"stream","text":["Celsius    Fahrenheit\n","---------------------\n","   0           32\n","  10           50\n","  20           68\n","  30           86\n","  40          104\n","  50          122\n","  60          140\n","  70          158\n","  80          176\n","  90          194\n"," 100          212\n","---------------------\n"]},{"data":{"text/plain":[""]},"execution_count":70,"metadata":{},"output_type":"execute_result"}],"source":["%%shell\n","\n","gcc E03_05.c -o E03_05\n","./E03_05 "]},{"cell_type":"markdown","metadata":{"id":"3DslPAFlqpNP"},"source":["##Example 6\n","### `++` and `--` operators\n","### Nested loops"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":509,"status":"ok","timestamp":1646141532233,"user":{"displayName":"HT Chen","photoUrl":"https://lh3.googleusercontent.com/a/default-user=s64","userId":"17748361917871513601"},"user_tz":-480},"id":"Y9haw6Ybqsqh","outputId":"bebd236b-4e69-4889-8797-43760cb2ee2a"},"outputs":[{"name":"stdout","output_type":"stream","text":["Overwriting E03_06.c\n"]}],"source":["%%writefile E03_06.c\n","#include <stdio.h>\n","\n","int main(void)\n","{\n","    int i, j;\n","\n","    i = 1;\n","    while (i<=9) {\n","        printf(\"i=%d: \", i);\n","        j = 1;\n","        while (j<=9-i){\n","            printf(\"    \");\n","            j++;\n","        }\n","        while (j<=9) {\n","            printf(\"%3d \", i*j);\n","            j++;\n","        }\n","        printf(\"\\n\");\n","        i++;\n","    }\n","\n","\n","    return 0;\n","}"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":616,"status":"ok","timestamp":1646141536514,"user":{"displayName":"HT Chen","photoUrl":"https://lh3.googleusercontent.com/a/default-user=s64","userId":"17748361917871513601"},"user_tz":-480},"id":"gn3ppit0rASc","outputId":"ee7c6802-5520-420d-caab-74a4ed24bff6"},"outputs":[{"name":"stdout","output_type":"stream","text":["i=1:                                   9 \n","i=2:                              16  18 \n","i=3:                          21  24  27 \n","i=4:                      24  28  32  36 \n","i=5:                  25  30  35  40  45 \n","i=6:              24  30  36  42  48  54 \n","i=7:          21  28  35  42  49  56  63 \n","i=8:      16  24  32  40  48  56  64  72 \n","i=9:   9  18  27  36  45  54  63  72  81 \n"]},{"data":{"text/plain":[""]},"execution_count":88,"metadata":{},"output_type":"execute_result"}],"source":["%%shell\n","\n","gcc E03_06.c -o E03_06\n","./E03_06"]},{"cell_type":"markdown","metadata":{"id":"l2w8CXaErKcg"},"source":["注意事項: \n","1. 初始值在甚麼地方設定; \n","2. 迴圈繼續執行的條件是否正確; \n","3. 變數狀態是否會更新 (否則迴圈會無法結束)"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":298,"status":"ok","timestamp":1646736231877,"user":{"displayName":"HT Chen","photoUrl":"https://lh3.googleusercontent.com/a/default-user=s64","userId":"17748361917871513601"},"user_tz":-480},"id":"tTjyQaK6GtiP","outputId":"ba3d72f0-8821-4ac2-8107-9c0e7ff16e6c"},"outputs":[{"name":"stdout","output_type":"stream","text":["Overwriting E03_062.c\n"]}],"source":["%%writefile E03_062.c\n","#include <stdio.h>\n","int main(void)\n","{\n","    unsigned int i = 2147483648;\n","    while (i > 0) {\n","        printf(\"%d \", i);\n","        i++;\n","    }\n","     printf(\"%d \", i);\n","    return 0;\n","}"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"background_save":true,"base_uri":"https://localhost:8080/"},"id":"4gvXrJ2bHAXy","outputId":"50c3fe70-f449-4a11-8c59-359fd209fc85"},"outputs":[],"source":["%%shell\n","gcc E03_062.c -o E03_062\n","./E03_062"]},{"cell_type":"markdown","metadata":{"id":"Tgxixt6ywNp1"},"source":["##Example 7\n","###Two dimensional arrays"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"gQGtjE5xwgOd"},"outputs":[],"source":["%%writefile E03_07.c\n","#include <stdio.h>\n","\n","int main(void)\n","{\n","    int i, j;\n","    int a[10][10] = {0}; \n"," \n","    i = 1;\n","    while (i<=9) \n","    {\n","        j = 1;\n","        while (j<=9)\n","        {\n","            a[i][j] = ??? /* a[i][j] ith row, jth column */\n","            j = j + 1;\n","        }\n","        i = i + 1;\n","    }\n"," \n","    /* show the content of a */\n","    i = 1;\n","    while (i<=9) \n","    {\n","        j = 1;\n","        while (j<=9)\n","        {\n","            printf(\"%3d \", a[i][j]);\n","            j = j + 1;\n","        }\n","        printf(\"\\n\");\n","        i = i + 1;\n","    }\n"," \n","    return 0;\n","}\n","/*\n","How to print a Pascal Triangle?\n","Try it yourself.\n","0 0 0 0 0 0\n","0 1 0 0 0 0\n","0 1 1 0 0 0\n","0 1 2 1 0 0\n","0 1 3 3 1 0\n","0 1 4 6 4 1\n","...\n","*/"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"bhGdXW5Gwn9A"},"outputs":[],"source":["%%shell\n","gcc E03_07.c -o E03_07\n","./E03_07"]},{"cell_type":"markdown","metadata":{"id":"RoYXFRxkqzRX"},"source":["###要產生一個 5-by-5 two-dimensional array 可以用底下的寫法\n","```\n","int a[5][5];\n","```\n","可以想成這種樣子:\n","```\n","a[0][0]  a[0][1]  a[0][2]  a[0][3]  a[0][4]\n","a[1][0]  a[1][1]  a[1][2]  a[1][3]  a[1][4]\n","a[2][0]  a[2][1]  a[2][2]  a[2][3]  a[2][4]\n","a[3][0]  a[3][1]  a[3][2]  a[3][3]  a[3][4]\n","a[4][0]  a[4][1]  a[4][2]  a[4][3]  a[4][4]\n","```\n","\n"]},{"cell_type":"markdown","metadata":{"id":"O2_7-jmApclg"},"source":["###一些有的沒的\n","\n","* `a++` 與 `++a` 的差別?\n","\n","* `'A'` 與 `65` 的差別?\n","```\n","#include <stdio.h>\n","int main(void)\n","{\n","   int i = 'A';\n","   \n","   while (i <= 'Z') {\n","      printf(\"  %c: %3d\", i, i);\n","      i++;\n","   }\n","   return 0;\n","}\n","```\n","\n","* Expressions:\n","每個 expression 都代表某個值。包括像 5>3 這類條件判斷，也會依照條件是 true 或 false，而用對應的數值表示。\n","非零的值代表 true (通常用 1)，零則表示 false。\n","\n","\n","* 型別轉換的規則與強制型別轉換 \n","\n","* `>`, `<`, `>=`, `<=`, `==`, `!=` 關係判斷符號\n","\n","* `+=`, `-=`, `*=`, `/=`, `%=` 其他 assignment 符號"]},{"cell_type":"markdown","metadata":{"id":"Uzp4SPICqD8x"},"source":["##Example 8\n","\n","利用 scanf 傳回的值判斷 scanf 是否讀取到預期的輸入資料\n","```\n","x = scanf(\"%d\", &n);\n","```\n"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"z0EZ1L-ZqNAZ"},"outputs":[],"source":["%%writefile E03_08.c\n","\n","#include <stdio.h>\n","int main(void)\n","{\n","   long num;\n","   long sum = 0L;\n","   int status;\n","\n","   printf(\"Please enter an integer to be summed \");\n","   printf(\"(q to quit): \");\n","   status = scanf(\"%ld\", &num); /* %ld for long */\n","   /*printf(\"status: %d\\n\", status);*/\n","   while (status == 1) {        /* == means \"is equal to\" */\n","      sum = sum + num;\n","      printf(\"Please enter next integer (q to quit): \");\n","      status = scanf(\"%ld\", &num);\n","      /* printf(\"status: %d\\n\", status); */\n","   }\n","   printf(\"Those integers sum to %ld.\\n\", sum);\n","\n","   return 0;\n","}"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"background_save":true},"id":"kinTEwEOqXG3"},"outputs":[],"source":["%%shell\n","gcc E03_08.c -o E03_08\n","./E03_08"]},{"cell_type":"markdown","metadata":{"id":"9h6JSk0lqdJ3"},"source":["####底下的程式碼是錯的\n","####找出錯誤並解釋錯誤發生的過程\n","\n","```\n","#include <stdio.h>\n","int main(void)\n","{\n","   long num;\n","   long sum = 0L;\n","   int status;\n","\n","   printf(\"Please enter an integer to be summed \");\n","   printf(\"(q to quit): \");\n","   status = scanf(\"%ld\", &num); /* %ld for long */\n","   /*printf(\"status: %d\\n\", status);*/\n","   while (status = 1) {        /* == means \"is equal to\" */\n","      sum = sum + num;\n","      printf(\"Please enter next integer (q to quit): \");\n","      status = scanf(\"%ld\", &num);\n","      /* printf(\"status: %d\\n\", status); */\n","   }\n","   printf(\"Those integers sum to %ld.\\n\", sum);\n","\n","   return 0;\n","}\n","```"]},{"cell_type":"markdown","metadata":{"id":"0d4UAr5qqtX3"},"source":["##Example 9\n","####用 EOF 判斷輸入是否結束\n","\n","檔案的結尾一定會有 `EOF` 字元，因此可以用 `EOF` 判斷是否已經將檔案讀完\n","如果是用手動方式輸入，則要在行首打 `Ctrl+Z` 再按 `Enter` 就可以打出 `EOF` 字元\n"]},{"cell_type":"code","execution_count":14,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"CQeIyJMmq3HB","executionInfo":{"status":"ok","timestamp":1646741065279,"user_tz":-480,"elapsed":302,"user":{"displayName":"HT Chen","photoUrl":"https://lh3.googleusercontent.com/a/default-user=s64","userId":"17748361917871513601"}},"outputId":"ecd6d4da-ad40-4a92-eae4-f8e1c3e3e7de"},"outputs":[{"output_type":"stream","name":"stdout","text":["Overwriting E03_09.c\n"]}],"source":["%%writefile E03_09.c\n","\n","#include <stdio.h>\n","\n","int main(void)\n","{\n","    int x, y;\n","// EOF end of file\n","    while (scanf(\"%d%d\", &x, &y) == 2) { /*Ctrl Z + Enter */\n","        printf(\"x=%d y=%d\\n\", x, y);\n","    }\n","    return 0;\n","}"]},{"cell_type":"code","execution_count":15,"metadata":{"id":"NMwxbHLmrEUw","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1646741069914,"user_tz":-480,"elapsed":318,"user":{"displayName":"HT Chen","photoUrl":"https://lh3.googleusercontent.com/a/default-user=s64","userId":"17748361917871513601"}},"outputId":"2cd14315-a15a-4775-86aa-2bb5beb3808f"},"outputs":[{"output_type":"stream","name":"stdout","text":["a.out\t E03_062.c  E03_07.c  E03_08.c\tE03_09.c     test.c\n","E03_062  E03_07     E03_08    E03_09\tsample_data  testcase\n","10 20 30 40 50\n","x=10 y=20\n","x=30 y=40\n"]},{"output_type":"execute_result","data":{"text/plain":[""]},"metadata":{},"execution_count":15}],"source":["%%shell\n","echo \"10 20 30 40 50\" > testcase\n","ls \n","cat testcase\n","gcc E03_09.c -o E03_09\n","./E03_09 < testcase"]},{"cell_type":"markdown","metadata":{"id":"U-1IVwfjrR9-"},"source":["##Example 10\n","###`for` loops"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"ngPTv5_6rQnC"},"outputs":[],"source":["%%writefile E03_10.c\n","\n","#include <stdio.h>\n","int b[10000][10000];\n","int main(void)\n","{\n","    int i, j;\n","\n","    printf(\"Go!\\n\");\n","    for (i = 0; i < 10000; i++) {\n","        for (j = 0; j < 10000; j++) {\n","            b[i][j] = i*j;\n","        }\n","    }\n","    printf(\"Done.\\n\");\n","\n","    for (i = 1; i <= 9; i++) {\n","        for (j = 1; j <= 9; j++) {\n","            printf(\"%3d\", b[i][j]);\n","        }\n","        printf(\"\\n\");\n","    }\n","\n","    return 0;\n","}\n"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"yuBFF8vyrgID"},"outputs":[],"source":["%%shell\n","gcc E03_10.c -o E03_10\n","./E03_10"]},{"cell_type":"markdown","metadata":{"id":"IIvrUDt3r4vq"},"source":["##Exercise 1\n","\n","輸入: `ABCDE`\n","\n","輸出:\n","```\n","     A\n","    AB\n","   ABC\n","  ABCD\n"," ABCDE\n","```\n","把下面程式碼 ??? 填入正確的運算式，讓程式可以達到預期的效果。\n","```\n","#include <stdio.h>\n","#include <???.h>\n","int main(void)\n","{\n","   int i = 1, word_len;\n","   char word[40];\n","   scanf(\"???\", ???);\n","\n","   word_len = strlen(word);\n","\n","   while (i <= word_len) {\n","      printf(\"%???\", ???, ???, word);\n","      i++;\n","   }\n","\n","   return 0;\n","}\n","```"]},{"cell_type":"markdown","metadata":{"id":"favQsltmr-Mr"},"source":["##Exercise 2 \n","輸入: `13579`\n","\n","輸出:\n","``` \n","     The number 13579 can be expressed as\n","     9 + 7*10+ 5*100 + 3*1000 + 1*10000.\n","```\n","把下面程式碼 ??? 填入正確的運算式，讓程式可以達到預期的效果。\n","\n","```\n","#include <stdio.h>\n","int main(void)\n","{\n","    int i, k;\n","    scanf(\"%d\", &i);\n","    printf(\"The number %d can be expressed as\\n\", i);\n","    k = 1;\n","    \n","    while (???) {\n","        printf(\"%d*%d + \", ???, ???);\n","        i = ???;\n","        k = ???;\n","    }\n","    // printf(\"\\b\\b\\b.  \\n\");\n","    \n","    return 0;\n","}\n","```"]},{"cell_type":"code","source":["%%writefile W03_02.c\n","#include <stdio.h>\n","#include <string.h>\n","int main(void)\n","{\n","    int i;\n","    char num[100];\n","    char num2[100];\n","    scanf(\"%s\", num);\n","    scanf(\"%s\", num2);\n","    printf(\"The number %d can be expressed as\\n\", i);\n","\n","    i = strlen(num) - 1;\n","    while (i >= 0) {\n","        printf(\" %d \", num[i]-'0');\n","        i--;\n","    }\n","    // printf(\"\\b\\b\\b.  \\n\");\n","\n","    return 0;\n","} "],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"8jdXM9sAbZ4_","executionInfo":{"status":"ok","timestamp":1646741872672,"user_tz":-480,"elapsed":367,"user":{"displayName":"HT Chen","photoUrl":"https://lh3.googleusercontent.com/a/default-user=s64","userId":"17748361917871513601"}},"outputId":"83932761-c844-44e6-8f07-d8255981307e"},"execution_count":34,"outputs":[{"output_type":"stream","name":"stdout","text":["Overwriting W03_02.c\n"]}]},{"cell_type":"code","source":["%%shell\n","gcc W03_02.c -o W03_02\n","./W03_02"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"oDkWcb-SbwOK","executionInfo":{"status":"ok","timestamp":1646741883373,"user_tz":-480,"elapsed":6207,"user":{"displayName":"HT Chen","photoUrl":"https://lh3.googleusercontent.com/a/default-user=s64","userId":"17748361917871513601"}},"outputId":"0f0186b2-21c9-418c-fd1c-1d4d825c9e0a"},"execution_count":35,"outputs":[{"output_type":"stream","name":"stdout","text":["18348173298471983748917348719237498137247123412341234\n","The number 0 can be expressed as\n"," 4  3  2  1  4  3  2  1  4  3  2  1  7  4  2  7  3  1  8  9  4  7  3  2  9  1  7  8  4  3  7  1  9  8  4  7  3  8  9  1  7  4  8  9  2  3  7  1  8  4  3  8  1 "]},{"output_type":"execute_result","data":{"text/plain":[""]},"metadata":{},"execution_count":35}]},{"cell_type":"markdown","metadata":{"id":"49ED7Jh8sLXt"},"source":["## Exercise 3\n","####使用者輸入想要顯示的長方形的高度和寬度，輸出一個由 * 構成且符合使用者輸入之大小的長方形。可以使用額外的變數 `k`，也可以只用到 `i` 和 `j` (利用 `%` 符號做求餘數的運算)。把下面程式碼 `???` 填入正確的運算式，讓程式可以達到預期的效果。\n","\n","```\n","#include <stdio.h>\n","int main(void)\n","{\n","    int i, j, k; \n","    scanf(\"%d%d\", &i, &j); \n","    for(???; ???; ???) { \n","        for (???; ???; ???) { \n","            printf(\"*\");\n","        }\n","        printf(\"\\n\");\n","    }      \n","\n","    return 0;\n","}\n","```"]}],"metadata":{"colab":{"name":"Week03.ipynb","provenance":[],"authorship_tag":"ABX9TyNC56w9q06Wi8TZgZnd/cur"},"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"name":"python"}},"nbformat":4,"nbformat_minor":0}