使用 C++ 中的遞迴列印金字塔


本文旨在透過使用 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;
}

在編譯上述程式碼後,將打印出帶有特殊字元“#”的金字塔,如下所示。

輸出

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

更新於:16-Jan-2020

檢視 833 次

開啟你的 職業生涯

完成該課程以獲得認證

開始
廣告