This python program generates or prints rectangular pattern made up of stars up to n lines.
Python Source Code: Rectangular Pattern
# Rectangular pattern in Python
# Reading number of rows and columns
row = int[input["Enter number of rows: "]]
col = int[input["Enter number of columns: "]]
print["Rectangular pattern is: "]
for i in range[1,row+1]:
for j in range[1,col+1]:
print["*", end=""]
print[]
Output: Rectangular Pattern
Enter number of rows: 4
Enter number of columns: 12
Rectangular pattern is:
************
************
************
************
In this shot, we will discuss how to generate a rectangle pattern using stars in Python. Numerous patterns can be printed using python, once we have a strong grip over the concepts involving loops. Here we will be using simple for
loops to generate a rectangle pattern using stars.
Description
To execute a rectangular pattern using Python programming, we will use 2 for
loops:
- Outer loop: It is used to iterate over the number of rows.
- Inner nested loop: It is used to iterate over the number of columns in each row.
Code
Let’s look at the code snippet below.
# Initialising Length and Breadth rows = 3 columns = 6 # Loop through number of rows for i in range[rows]: # Loop through number of columns for j in range[columns]: # Printing Pattern print['*', end = ' '] print[]
Explanation
- In line 2, we take the input for the number of rows.
- In line 3, we take the input for the number of columns.
- In line 6, we create a
for
loop to iterate through the number of rows. - In line 9, we create a
for
loop to iterate through the number of columns. - In lines 12 and 13, we print the pattern.
- The end statement is used to stay on the same line.
- The
print[]
statement is used to move to the next line.
View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
Given height h and width w, print a rectangular pattern as shown in the example below.
Examples:
Input : h = 4, w = 5 Output : @@@@@ @ @ @ @ @@@@@ Input : h = 7, w = 9 Output : @@@@@@@@ @ @ @ @ @ @ @ @ @ @ @@@@@@@@
The idea is to run two loops. One for the number of rows to be printed and the other for the number of columns. Print a ‘@’ only when the current row is first or last. OR the current column is first or last.
C++
#include
using
namespace
std;
void
printRectangle[
int
h,
int
w]
{
for
[
int
i=0; i
Output
@@@@@ @ @ @ @ @@@@@
Time complexity: O[n2], Space Complexity: O[1] // Constant space.
This article is contributed by Anurag Rawat. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to . See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.