Open In App

Recursive program to print triangular patterns

Last Updated : 13 Mar, 2023
Comments
Improve
Suggest changes
Like Article
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++




// C++ program to print triangular patterns using Recursive
#include <iostream>
  
using namespace std;
void printPartten(int n, int k)
{
    if (n < 0) // Base condition
        return;
  
    // Recursive call
    printPartten(n - 1, k + 1); 
  
    int i;
    for (i = 0; i < k; i++) // it makes spaces
        cout << " ";
    for (i = 0; i < n; i++) // for print *
        printf("* ");
    printf("\n"); // for next line
}
  
int main()
{
    int n = 7;
  
    // Call to printPartten function
    printPartten(n, 0); 
    return 0;
}


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++ program to print reverse triangular 
// patterns using Recursive
#include <bits/stdc++.h>
using namespace std;
  
void printPartten(int n, int k)
{
    if (n < 0) // Base condition
        return;
    int i;
    for (i = 0; i < k; i++) // it makes spaces
        cout <<" ";
    for (i = 0; i < n; i++) // for print *
        cout <<"* ";
    cout <<"\n"; // for next line
  
    // Recursive calls
    printPartten(n - 1, k + 1); 
}
  
int main()
{
    int n = 7;
  
    // Call to printPartten function
    printPartten(n, 0); 
    return 0;
}
// this code is contributed by shivanisinghss2110


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.



Next Article

Similar Reads