# 函式(function) ## 函式介紹 📖 函式在C語言中,有相當重要的地位,他可以避面許多繁瑣的步驟,並將自己的程式變得淺顯易懂。 之前有提到過printf()的由來,它的本質上也是一個函式。(include在stdio.h函式庫中) ![](https://hackmd.io/_uploads/BJf_KOCZ6.png =70%x) ### 函式的特色: 1. 一段程式碼,執行特別的工作。 2. 可重複使用 3. 讓程式變得淺顯易懂 4. 在呼叫函式不變的狀況下,可以直接修改程式。 ### 函式的語法 ``` 回傳型別 函式的名稱(參數型別宣告) { 程式碼主體 } ``` - 回傳型別:這個函式要回傳的值是什麼(ex: void 不回傳) - 函式的名稱:宣告這個函式要叫什麼 - 參數型別宣告:函式中的參數不一定只有一個,可以有一個,兩個或多個參數。 ### 示範Code👉 ```c #include <stdio.h> int square(int h, int l) { printf("Height is %d and Length is %d\n", h, l); return h*l; } int main() { int h = 5 , l = 3; int area = square(5, 3); printf("The area is %d !!\n", area); return 0; } ``` ## 函式的宣告 `回傳值型態 函式名稱 (參數)` ### 目的 在主程式(main)上方,告訴他我們所寫的函式原型大概長怎樣 這樣在跑得時候才不會找不到,然後出問題 ### 示範Code👉 ```c #include <stdio.h> int square(int, int); int main() { int h = 5 , l = 3; int area = square(5, 3); printf("The area is %d !!\n", area); return 0; } int square(int h, int l) { printf("Height is %d and Length is %d\n", h, l); return h*l; } ``` [貪吃蛇](https://hackmd.io/@9kGtv8nKSxCgFLkzWi7aSw/rJ_yNM8z6) ## 遞迴 ### 遞迴介紹 📖 1. 先將一個大問題,拆解成幾個較小的問題 2. 每個較小的問題,又能依照相同方式拆成更小的問題 3. 每當小問題解決時,大問題也可以依靠小問題的結果來解決 4. 每層的解決方法都是一樣的,除了最小的問題以外 5. 根據以上幾點,我們可以不斷套用相同的函數,讓他自己幫自己解決問題 ![](https://hackmd.io/_uploads/SJEKqcAW6.png =70%x) ### 示範Code👉 計算兩個數字的最大公因數 ```c #include<stdio.h> int gcd(int, int); int main() { int a = 28 , b = 16; printf("%d\n", gcd(a, b)); return 0; } int gcd (int n, int m) { if(m == 0) { return n; } return gcd(m, n%m); } ``` --- 課堂練習: [function_practice](https://www.w3schools.com/c/exercise.php?filename=exercise_functions1) 參考: [function](https://mycollegenotebook.medium.com/%EF%BD%83%E8%AA%9E%E8%A8%80%E7%AD%86%E8%A8%98-%E5%87%BD%E5%BC%8F-functions-cea21d86560f) [GCD](https://openhome.cc/Gossip/CGossip/Recursion.html) [遞迴](https://medium.com/appworks-school/%E9%80%B2%E5%85%A5%E9%81%9E%E8%BF%B4-recursion-%E7%9A%84%E4%B8%96%E7%95%8C-%E4%B8%80-59fa4b394ef6)