Printing Pyramid using Recursion in C++


This article aims to print a pyramid pattern by using the recursive implementation of C++ programming. Here is the algorithm as following to do so;

Algorithm

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

Example

As said the above algorithm, the following genuine C++ code economics is written as following;

 Live Demo

#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;
}

After compilation of the above code, the pyramid with the association of special character “#” will be printed looks like as.

Output

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

Updated on: 16-Jan-2020

712 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements