Skip to content

Table of Contents

SNo.Link
1Right-angled Triangle
2Inverted Right-angled Triangle
3Centered Half Pyramid

1. Right-angled Triangle

python
#Expected Output for number of rows = 5
*
**
***
****
*****

To build the logic, always represent the pattern in a tabular format.

R\Cj=1j=2j=3j=4j=5
i=1*
i=2**
i=3***
i=4****
i=5*****
  • We can observe that '*' is being printed up to i<=j
  • Usually we need two loops for printing i.e. ith loop for rows and jth loop for columns (Basic understanding)
  • ith loop iterates up to n (inclusive) where as jth loop iterates up to i (inclusive)

Code for it can be written as follows:

python
n=int(input()) #no. of rows
for i in range(1,n+1):
    for j in range(1,i+1):
        print('*',end='')
    print()
  • end is an optional argument for print(), it tells what should be printed at the end of the output.
  • It is used to bypass the default \n argument allowing '*' to appear side by side.
  • we use 'print()' as a \n allowing subsequent iterations to print in fresh rows.

Output without using end and print()

python
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*

Since python supports String Multiplication, above code can also be written as follows:

python
n=int(input())
for i in range(1, n+1):
    print("*" * i)

at i=1 it prints 1 '*' (1 * '*' = *)
at i=2 it prints 2 '*' (2 * '*' = **) and so on..

2. Inverted Right-angled Triangle

python
#Expected Output for number of rows = 5
    *
   **
  ***
 ****
*****

Tabular representation:

R\Cj=1j=2j=3j=4j=5
i=1*
i=2**
i=3***
i=4****
i=5*****

To solve this, check where the '*' is being printed (i.e. no. of white spaces).

  • at i=1, 4 white spaces and 1 '*'
  • at i=2, 3 white spaces and 2 '*'
  • at i=3, 2 white spaces and 3 '*'
  • at i=4, 1 white spaces and 4 '*'
  • at i=5, 0 white spaces and 5 '*'

White spaces are being decreased where as '*' as being increased row by row.
=> no. of white spaces: n-i and no. of '*' : i

python
n=int(input())
for i in range(1,n+1):
    for j in range(n-i): #Loop runs for n-i times, since we have n-i white spaces
        print(' ',end='')
    for k in range(i): #Loop runs for i times, since we have i '*'
        print('*',end='')
    print()

It can also be wriiten as:

python
n=int(input())
for i in range(1,n+1):
    print(' '*(n-i)+'*'*i) #String concatenation

3. Centered Half Pyramid

python
#Expected Output
    *
   * *
  * * *
 * * * *
* * * * *

Tabular representation:

*W
*W*W
*W*W*W
*W*W*W*W
*W*W*W*W*

Here, W is the white space.

python
n=int(input())
for i in range(1,n+1):
    for j in range(n-i):
        print(' ',end='')
    for k in range(i): 
        print('*',end=' ')
    print()

Under Construction