C program to print square or rectangle star pattern

Write a C program to print square star(*) pattern series of N rows.

Logic to print square star pattern of N rows in C programming.

Logic to print square star pattern

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

Have a close look to the pattern first so that you can understand the logic we are going to understand.

The pattern is a matrix of N rows and columns containing stars(asterisks). Here, you need to iterate through N rows, and for each row iterate for N columns.

Step by step descriptive logic to print the square number pattern.

  1. Input number of rows from user. Store it in some variable say N.
  2. To iterate through rows, run an outer loop from 1 to N. The loop structure should be similar to for(i=1; i<=N; i++).
  3. To iterate through columns, run an inner loop from 1 to N. Define a loop inside above loop with structure for(j=1; j<=N; j++).
  4. Inside inner loop print *.
  5. After printing all columns of a row move to next line i.e. print a new line.

Let us implement the given pattern in C program.

Program to print square star pattern

/**
 * C program to print square star pattern
 */

#include <stdio.h>
int main()
{
    int i, j, N;

    /* Input number of rows from user */
    printf("Enter number of rows: ");
    scanf("%d", &N);

    /* Iterate through N rows */
    for(i=1; i<=N; i++)
    {
        /* Iterate over columns */
        for(j=1; j<=N; j++)
        {
            /* Print star for each column */
            printf("*");
        }
        
        /* Move to the next line/row */
        printf("\n");
    }

    return 0;
}

Output

Happy Code Decoding 😉 …

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s