Print the given pattern recursively

In C programming, we can create various patterns using recursive functions. A recursive function is one that calls itself repeatedly until a base condition is met. Here we'll learn to print a star pattern where each row contains an increasing number of stars.

Syntax

void printStars(int n);
void printPattern(int n);

Algorithm

START
Step 1 ? function printStars(int n)
   If n > 0
      printStars(n-1)
      Print *
   End IF
End

Step 2 ? function printPattern(int n)
   If n > 0
      printPattern(n-1)
   End IF
   printStars(n)
   Print newline
End
STOP

Example: Recursive Star Pattern

This program prints a triangular pattern where row i contains i stars −

#include <stdio.h>

void printStars(int n) {
    if (n > 0) {
        printStars(n - 1);
        printf("*");
    }
}

void printPattern(int n) {
    if (n > 0) {
        printPattern(n - 1);
    }
    printStars(n);
    printf("<br>");
}

int main() {
    int n = 7;
    printf("Printing star pattern for n = %d:<br>", n);
    printPattern(n);
    return 0;
}
Printing star pattern for n = 7:
*
**
***
****
*****
******
*******

How It Works

  • printStars(n): Recursively prints n stars in a single row
  • printPattern(n): First calls itself for (n-1), then prints n stars followed by newline
  • Base case: When n becomes 0, recursion stops
  • The recursion ensures rows are printed in ascending order (1 star, 2 stars, etc.)

Key Points

  • The recursive approach naturally handles the pattern generation without explicit loops
  • Time complexity is O(n²) due to nested recursive calls
  • Space complexity is O(n) for the recursion stack

Conclusion

Recursive functions provide an elegant way to generate patterns by breaking the problem into smaller subproblems. This approach is particularly useful for understanding recursion concepts in C programming.

Updated on: 2026-03-15T11:09:14+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements