Here, we will print hollow rectangle star(*) pattern by using for loop in C programming language.
Consider an example given below −
Input
Enter number of rows: 5
Output
The output is as follows −
***** * * * * * * *****
Algorithm
An algorithm is given below to explain how to print hollow rectangle star(*) pattern by using for loop.
Step 1 − Input number of rows to print at runtime.
Step 2 − Use outer for loop for rows from 1 to N.
for(i=1; i<=N; i++)
Step 3 − Run an inner loop from 1 to N for columns.
for(j=1; j<=N; j++).
Step 4 − Inside inner loop print star for first and last row or for first and last column.
Otherwise, print space.
Step 5 − After printing all columns of a row, move to next line.
Program
Following is the C program to print hollow rectangle star(*) pattern by using for loop −
#include <stdio.h> int main(){ int i, j, N; printf("Enter number of rows: "); scanf("%d", &N); for(i=1; i<=N; i++) { for(j=1; j<=N; j++){ if(i==1 || i==N || j==1 || j==N){ printf("*"); } else{ printf(" "); } } printf("\n"); } return 0; }
Output
When the above program is executed, it produces the following result −
Enter number of rows: 6 ****** * * * * * * * * ******