Open In App

Recursive program to print triangular patterns

Last Updated : 13 Mar, 2023
Comments
Improve
Suggest changes
4 Likes
Like
Report

We have discussed iterative pattern printing in previous post

Examples: 

Input : 7
Output :                    
      *
     * *
    * * *
   * * * * 
  * * * * *
 * * * * * *
* * * * * * *

Algorithm:- 
step 1:- first think for the base condition i.e. number less than 0 
step 2:-do the recursive calls till number less than 0 i.e:- printPartten(n-1, k+1); 
step 3:-print the spaces 
step 4:-then print * till number

Below is the implementation of above approach:

C++
Java Python3 C# PHP JavaScript

Output: 
      * 
     * * 
    * * * 
   * * * * 
  * * * * * 
 * * * * * * 
* * * * * * *

 

Time Complexity: O(n2)
Auxiliary Space: O(n), The extra space is used in recursion call stack.

How to print its reverse pattern? 
simply Just put the recursive line end of the function 

Example: 

Input : 7
Output : 
* * * * * * *
 * * * * * * 
  * * * * *    
   * * * *  
    * * *    
     * *          
      *
C++
C Java Python 3 C# PHP JavaScript

Output: 
* * * * * * * 
 * * * * * * 
  * * * * * 
   * * * * 
    * * * 
     * * 
      *

 

Time Complexity: O(n2)
Auxiliary Space: O(1), As the function becomes tail recursive no extra stack space is required.


Similar Reads