Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

พิมพ์พีระมิดด้วย Recursion ใน C++

บทความนี้มีจุดประสงค์เพื่อพิมพ์รูปแบบพีระมิดโดยใช้ recursive implementation ของ C++ programming นี่คืออัลกอริทึมดังนี้:

อัลกอริทึม

ขั้นตอนที่ 1 กำหนดความสูงของพีระมิด
ขั้นตอนที่ 2 ปรับ space โดยใช้ recursion function
ขั้นตอนที่ 3 ปรับ Hash(#) character โดยใช้ recursion function
ขั้นตอนที่ 4 เรียกทั้งสองฟังก์ชันร่วมกันเพื่อพิมพ์รูปแบบพีระมิด

โปรแกรมตัวอย่าง

ตามอัลกอริทึมข้างต้น โค้ด 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;
}

หลังจากคอมไพล์โค้ดข้างต้น พีระมิดกับตัวอักษรพิเศษ "#" จะถูกพิมพ์ออกมาเหมือนนี้:

ผลลัพธ์

    #
   # #
  # # #
 # # # #
# # # # #