How to write a C Program to Print Rectangle Star Pattern with an example? And also show you how to print a Rectangle pattern with different symbols.
C program to Print Rectangle Star Pattern
This C program allows the user to enter the number of rows and columns. These values will decide the number of rows and columns of a rectangle. Here, we are going to print the stars until it reaches the user-specified rows and columns.
#include<stdio.h> int main() { int i, j, rows, columns; printf("Please Enter the Number of rows:\n"); scanf("%d", &rows); printf("Please Enter the Number of Columns:\n"); scanf("%d", &columns); for(i = 0; i < rows; i++) { for(j = 0; j < columns; j++) { printf("*"); } printf("\n"); } return 0; }
Let us see the Nested for loop
for(i = 0; i < rows; i++) { for(j = 0; j < columns; j++) { printf("*"); } printf("\n"); }
Outer Loop – First Iteration
From the above C Programming screenshot, you can see that the value of i is 0 and Rows is 5, so the condition (i < 5) is True. So, it will enter into the second for loop
Inner Loop – First Iteration
The j value is 0 and the condition (j < 10) is True. So, it will start executing the statement inside the loop. The following statement will print *
printf("*");
The below statement will increment the Value of j by 1 using the Increment Operator.
j++
It will happen until it reaches 10, and after that, both the Inner Loop and Outer loop will terminate.
C Program to Print Rectangle Pattern with Dynamic Character
This rectangle pattern program allows the user to enter the Symbol that he/she wants to print as a rectangle pattern.
#include<stdio.h> int main() { int i, j, rows, columns; char Ch; printf("Please Enter any Symbol\n"); scanf("%c", &Ch); printf("Please Enter the Number of rows:\n"); scanf("%d", &rows); printf("Please Enter the Number of Columns:\n"); scanf("%d", &columns); for(i = 0; i < rows; i++) { for(j = 0; j < columns; j++) { printf("%c", Ch); } printf("\n"); } return 0; }
Please Enter any Symbol
#
Please Enter the Number of rows:
7
Please Enter the Number of Columns:
15
###############
###############
###############
###############
###############
###############
###############
C Program to Print Rectangle Pattern using While Loop
In this C program, we just replaced the For Loop with the While Loop. I suggest you refer While Loop article to understand the logic.
#include<stdio.h> int main() { int i, j, rows, columns; char Ch; printf("Please Enter any Symbol\n"); scanf("%c", &Ch); printf("Please Enter the Number of rows:\n"); scanf("%d", &rows); printf("Please Enter the Number of Columns:\n"); scanf("%d", &columns); i = 0; while(i < rows) { for(j = 0; j < columns; j++) { printf("%c", Ch); } printf("\n"); i++; } return 0; }
Please Enter any Symbol
*
Please Enter the Number of rows:
10
Please Enter the Number of Columns:
15
***************
***************
***************
***************
***************
***************
***************
***************
***************
***************