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 Square Pattern Using Recursion Function


Write a C program to Print Square Pattern using Recursion Function

  • print_row(n) recursionly prints n stars on the same line by printing one star and calling itself with n - 1.
  • print_square(size, current) recursionly prints size rows of stars by printing one row and calling itself with current - 1.
  • The base condition for both recursion functions ensures they stop when their respective counters reach 0.
  • The main() function initializes size = 4 and starts the pattern printing by calling print_square(size, size).
Example : pgm.c
#include <stdio.h>

// Recursion function to print a single row
void print_row(int n) {
    if (n == 0)
        return;
    printf("* ");
    print_row(n - 1);
}

// Recursion function to print the square pattern
void print_square(int size, int current) {
    if (current == 0)
        return;
    print_row(size);        // Print one row
    printf("\n");
    print_square(size, current - 1);  // Print remaining rows
}

int main() {
    int size = 4;

    print_square(size, size);

    return 0;
}

Output :

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