Basic

Switch Case

Goto

Operators

if Statement

Nested if

While Loop

For Loop

Patterns

Array

2D Array

String Function Example

Pointers

Recursion Function

Structure

Excersises

Others


C Program to Print Pyramid Pattern using Recursion Function


Write a C program to print pyramid pattern using recursion function.

  • print_spaces(count) recursionly prints count number of spaces for indentation before the stars.
  • print_stars(count) recursionly prints count number of stars on the same line to form the triangle row.
  • print_triangle(current, total) prints a row of the triangle by combining spaces and stars, then recursionly moves to the next row.
  • main() starts the triangle printing by calling print_triangle(1, size) for a triangle of height size = 4.
Example : pgm.c
#include <stdio.h>

// Recursion function to print spaces
void print_spaces(int count) {
    if (count == 0)
        return;
    printf(" ");
    print_spaces(count - 1);
}

// Recursion function to print stars
void print_stars(int count) {
    if (count == 0)
        return;
    printf("*");
    print_stars(count - 1);
}

// Recursion function to print each row
void print_triangle(int current, int total) {
    if (current > total)
        return;
    
    print_spaces(total - current);         // Print leading spaces
    print_stars(2 * current - 1);          // Print stars for current row
    printf("\n");
    
    print_triangle(current + 1, total);    // Move to next row
}

int main() {
    int size = 4;

    print_triangle(1, size);

    return 0;
}

Output :

   *   
  ***  
 ***** 
*******