이 기사는 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;
} 위의 코드를 컴파일하면 특수 문자 "#"가 연결된 피라미드가 다음과 같이 인쇄됩니다.
출력
# # # # # # # # # # # # # # #