Skip to content
Programming Exercises · Q9

Q.Write a program to print the following patterns:

i)
*


*
ii)
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
iii)
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
iv)
*
  • *
  • *  
    
Yanam CbseNCERTSubjective· 5mImportance★★★★★est
97% · 38/39 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

Every pattern is "for each row: print (leading spaces) + (row items)" — derive the two formulas per pattern (spaces from the row index, items from a star count or number run) and let nested loops / joins do the rest.

The idea. Pattern printing decomposes each row into indentation and content, both functions of the row index i. Diamonds are a growing half (i = 1…n) followed by a shrinking mirror (i = n-1…1).

i) Star diamond — row i has 2i-1 stars separated by spaces, indented so the middle row (i = n = 3) touches the margin:

n = 3
rows = list(range(1, n + 1)) + list(range(n - 1, 0, -1))
for i in rows:
    print("  " * (n - i) + " ".join("*" * (2 * i - 1)))
    *
  * * *
* * * * *
  * * *
    *

ii) Number pyramid — row i counts DOWN i…1 then UP 2…i, indented by 2 spaces per missing level:

n = 5
for i in range(1, n + 1):
    nums = list(range(i, 0, -1)) + list(range(2, i + 1))
    print("  " * (n - i) + " ".join(str(x) for x in nums))
        1
      2 1 2
    3 2 1 2 3
  4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5

iii) Shrinking number triangle — row lengths run i = 5 down to 1, each row printing 1…i and indented as it shrinks:

n = 5
for i in range(n, 0, -1):
    print("  " * (n - i) + " ".join(str(x) for x in range(1, i + 1)))
1 2 3 4 5
  1 2 3 4
    1 2 3
      1 2
        1

iv) Hollow diamond — only two stars per row (one at row 1), separated by a widening gap of 2i-1 spaces:

n = 3
for i in list(range(1, n + 1)) + list(range(n - 1, 0, -1)):
    if i == 1:
        print(" " * (n - i) + "*")
    else: …

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.