ที่นี่ ตามรูปแบบปัญหาที่กำหนดจะต้องแสดงโดยใช้วิธีการแบบเรียกซ้ำ
ฟังก์ชันแบบเรียกซ้ำ คือตัวที่เรียกตัวเองว่า n จำนวนครั้ง สามารถมีฟังก์ชันแบบเรียกซ้ำจำนวน 'n' ในโปรแกรมได้ ปัญหาในการทำงานกับฟังก์ชันแบบเรียกซ้ำคือความซับซ้อน
อัลกอริทึม
START Step 1 -> function int printpattern(int n) If n>0 Printpattern(n-1) Print * End IF End Step 2 -> function int pattern(int n) If n>0 pattern(n-1) End IF Printpattern(n) Print \n End STOP
ตัวอย่าง
#include <stdio.h>
int printpattern(int n) {
if(n>0) {
printpattern(n-1);
printf("*");
}
}
int pattern(int n) {
if(n>0) {
pattern(n-1); //will recursively print the pattern
}
printpattern(n); //will reduce the n recursively.
printf("\n"); //for new line
}
int main(int argc, char const *argv[]) {
int n = 7;
pattern(n);
return 0;
} ผลลัพธ์
หากเรารันโปรแกรมด้านบน มันจะสร้างผลลัพธ์ต่อไปนี้
* ** *** **** ***** ****** *******