- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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;
#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
# # # # # # # # # # # # # # #
Advertisements