Skip to content
Programs · Program 6-17

Q.Program 6-17: Program to print the pattern for a number input by the user.
The output pattern to be generated is
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Punjab PsebTextbookSubjective· 3mImportance★★★★★est
54% · 21/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 →

The pattern is n rows where row i holds the numbers 1 to i, so an outer loop runs i = 1…n and an inner loop prints 1…i on one line — the inner loop's length depends on the outer loop's variable.

The idea. Patterns are the signature use of nested loops: the outer loop selects the row, the inner loop prints that row's entries. The key observation here is that the inner range is not fixed — it is range(1, i + 1), i.e. the row number itself decides how many numbers appear.

# Program 6-17: print the pattern for a number input by the user
n = int(input("Enter the number of rows: "))
for i in range(1, n + 1):          # one pass per row
    for j in range(1, i + 1):      # row i carries the numbers 1..i
        print(j, end=" ")          # stay on the same line
    print()                        # end of row: move to the next line

Sample run (user enters 5)

Enter the number of rows: 5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Dry run

Row iInner j runs overPrinted on the line
111
21, 21 2
31, 2, 31 2 3
41…41 2 3 4
51…51 2 3 4 5

The two printing tricks …

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.