Page 223 - Computer Science Class 11 Without Functions
P. 223
9.7 Printing Patterns
In this section, we will learn to display some nice patterns. We begin with a right triangle of asterisks.
9.7.1 Right Triangle
A right triangle has one symbol in the first row, two in the second row, three in the third row, and so on. Let us write a
program to print such a triangle. The program will only require two inputs, the number of rows (say, nRows) and the
symbol (say, symbol) to be used in the pattern (see Program 9.11).
Program 9.11 To display the right triangular pattern of a symbol
01 '''
02 Objective: To display the right triangular pattern of a symbol
03 Inputs:
04 nRows : number of rows
05 symbol: symbol to be printed
06 Output: Pattern
07 '''
08 nRows = int(input('Enter the number of rows: '))
09 symbol = input('Enter Symbol: ')
10 for i in range(1, nRows + 1):
11 for j in range(1, i + 1):
12 print(symbol, end = '')
13 print()
Sample Output:
>>> Enter the number of rows: 6
>>> Enter Symbol: *
*
**
***
****
*****
******
In Topic 9.7.1 shows how to use nested for statements, there was a simpler way to do it using the repetition
operator *. Recall that the expression symbol*i yields a string of length i. So, using the repetition operator, Program
9.11 may be rewritten as Program 9.12.
Program 9.12 To display the right triangular pattern of a symbol using string.
01 '''
02 Objective: To display the right triangular pattern of a symbol
03 Inputs:
04 nRows : number of rows
05 symbol: symbol to be printed
06 Output: Pattern
07 '''
08 nRows = int(input('Enter the number of rows: '))
09 symbol = input('Enter Symbol: ')
10 for i in range(1, nRows + 1):
11 print(symbol*i,end='')
12 print()
9.7.2 Inverted Isosceles Triangle
Next, let us write a program to print an inverted isosceles triangle using a given symbol (say, symbol). Fig 9.7 shows
an inverted isosceles triangle comprising six rows using asterisks. Note that the first row does not have any leading
rd
nd
spaces, the 2 row has one leading space, 3 row has two leading spaces, and so on.
Looping in Python 221

