งานนำเสนอกำลังจะดาวน์โหลด โปรดรอ

งานนำเสนอกำลังจะดาวน์โหลด โปรดรอ

Recursion การเรียกซ้ำ

งานนำเสนอที่คล้ายกัน


งานนำเสนอเรื่อง: "Recursion การเรียกซ้ำ"— ใบสำเนางานนำเสนอ:

1 Recursion การเรียกซ้ำ

2 การเรียกซ้ำ (Recursion)
วิธีการที่ฟังก์ชันใดๆ สามารถเรียกตัวเองได้ แต่ละครั้งที่ฟังก์ชันถูกเรียก จะเกิดตัวแปรอัตโนมัติชุดใหม่ที่ไม่เกี่ยวกับชุดเดิม จึงเรียกวิธีนี้อีกชื่อหนึ่งว่า การเวียนเกิด จึงใช้เนื้อที่ในหน่วยความจำมาก และทำงานช้า วิธีการเรียกซ้ำแบบนี้ ทำให้มีรหัสคำสั่งขนาดกะทัดรัด เขียนและเข้าใจง่าย

3 ตัวอย่าง ๑ #include <stdio.h> /* Recursion not used */
void count_down (int n) { if (n) { printf(“%d ! ”, n); /* The recursive call */ count_down(n-1); } else printf(“\nBLAST OFF\n”); void main() { /* The initial call */ count_down(10); /* Recursion not used */ #include <stdio.h> void main () { int n; for (n=10; n; n--) printf(“%d ! ”, n); printf(“\n BLAST OFF\n”); } 10 ! 9 ! 8 ! 7 ! 6 ! 5 ! 4 ! 3 ! 2 ! 1 ! BLAST OFF

4 ตัวอย่าง หาผลบวกแบบเรียกซ้ำ
/* Compute sums recursively*/ int sum (int n) { if (n <= 1) return n; else return n + sum(n-1); } Function call Value returned sum(1) 1 sum(2) sum(1) หรือ 2 + 1 sum(3) sum(2) หรือ sum(4) sum(3) หรือ

5 ตัวอย่าง ฟังก์ชันแบบเรียกซ้ำที่ผิดพลาด
/* Forgetting the base case*/ long factorial (long n) { return n * factorial(n-1); } /* Incomplete base case test */ long factorial (long n) { if (n == 1) return 1; else return n * factorial(n-1); } factorial (0); /* Ambiguous use of decrement operator */ long factorial (long n) { if (n <= 1) return 1; else return n * factorial (- -n); }


ดาวน์โหลด ppt Recursion การเรียกซ้ำ

งานนำเสนอที่คล้ายกัน


Ads by Google