บทความนี้มีจุดมุ่งหมายเพื่อพิมพ์รูปแบบพีระมิดโดยใช้การเขียนโปรแกรม C++ แบบเรียกซ้ำ นี่คืออัลกอริธึมในการทำเช่นนั้น
อัลกอริทึม
Step-1 Set the height of the pyramid Step-2 Adjust space using recursion function Step-3 Adjust Hash(#) character using recursion function Step-4 Call both functions altogether to print the Pyramid pattern
ตัวอย่าง
ดังที่กล่าวไว้ในอัลกอริธึมข้างต้น เศรษฐศาสตร์โค้ด C++ ของแท้ต่อไปนี้ถูกเขียนดังนี้
#include <iostream>
using namespace std;
// function to print spaces
void print_space(int space){
if (space == 0)
return;
cout << " ";
// recursively calling print_space()
print_space(space - 1);
}
// function to print hash
void print_hash(int pat){
if (pat == 0)
return;
cout << "# ";
// recursively calling hash()
print_hash(pat - 1);
}
// function to print the pattern
void Pyramid(int n, int num){
// base case
if (n == 0)
return;
print_space(n - 1);
print_hash(num - n + 1);
cout << endl;
// recursively calling pattern()
Pyramid(n - 1, num);
}
int main(){
int n = 5;
Pyramid(n, n);
return 0;
} หลังจากคอมไพล์โค้ดข้างต้นแล้ว พีระมิดที่มีการเชื่อมโยงของอักขระพิเศษ “#” จะถูกพิมพ์ออกมามีลักษณะดังนี้
ผลลัพธ์
# # # # # # # # # # # # # # #