使用 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;
}在编译上述代码后,将打印出带有特殊字符“#”的金字塔,如下所示。
输出
# # # # # # # # # # # # # # #
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 程序设计
C++
C#
MongoDB
MySQL
Javascript
PHP