- Write a C program to print square star pattern of n rows using for loop.
For a square star pattern of side 5 stars. Program’s output should be:
Required Knowledge
- For Loop
- printf and scanf function in C
Algorithm to print square star pattern using loop
- Take the number of stars in each side of square as input from user using scanf function. Let it be N.
- We will use two for loops to print square star pattern.
- In one iteration, outer for loop will print one row of pattern.
- In one iteration, inner for loop will print one star (*) characters in a row.
Here is the matrix representation of the square star pattern. The row numbers are represented by i whereas column numbers are represented by j.
C program to print square star pattern
#include<stdio.h> int main(){ int side, i, j; printf("Enter side of square\n"); scanf("%d", &side); /* Row iterator for loop */ for(i = 0; i < side; i++){ /* Column iterator for loop */ for(j = 0; j < side; j++){ printf("*"); } printf("\n"); } return 0; }
Output
Enter side of square 5 ***** ***** ***** ***** *****