Introduction to Patterns

Patterns Definition : 

A pattern is an idea or design that solves a common problem in many different circumstances. Understanding programming patterns is the key to writing efficient, readable and maintainable code.

Patterns are a way of thinking about programming problems. They are a way to solve problems in a general way, rather than solving them each time you encounter them. Patterns provide a better understanding of loops and how to write efficient, readable and maintainable code.

How to Print Patterns?

  1. You have to first figure out the number of rows in the pattern.
  2. Figure out the number of columns.
  3. Focus on what to print.
  4. We have to use an outer loop for iterating the rows.
  5. Then use an inner nested loop that deals with the number of columns. 

Understand with an example:

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

Here, we have to print that pattern as shown above. How are we going to code that pattern?

Let's follow the mentioned steps:

Approach: 

  1. Number of rows: The given pattern has 4 rows.
  2. Number of columns: The given pattern has 4 rows.
  3. What to print: We have to print '*'.
  4. Use an outer loop for rows:  
  5. Use an inner nested loop for columns:

Using While loop:

i = 0
while i < 4 : #outer loop that deals with rows
    j = 0
    while j < 4: #inner loop that is for columns
        print('*', end = (''))
        j = j + 1
    print()
    i = i + 1

Using for loop:

for i in range(4) : #outer loop that deals with rows
    for j in range(4): #inner loop that is for columns
        print('*', end = (''))
    print()
Previous Post Next Post