CBSE Class 11 Computer Science Question 35 of 43

Flow of Control — Question 28

Back to all questions
28
Question

Question 24c

Write programs to print the following shapes:

   *
 *  *
*    *
 *  *
   *

Solution
n = 3 # number of rows

# upper half
for i in range(1, n+1) :
    # for loop for initial spaces
    for j in range(n, i, -1) :
        print(' ', end = '')

    #while loop for * and spaces
    x = 1
    while x < 2 * i :
        if x == 1 or x == 2 * i - 1 :
            print('*', end = '')
        else :
            print(' ', end = '')
        x += 1
    print()

# lower half
for i in range(n-1, 0, -1) :
    # for loop for initial spaces
    for j in range(n, i, -1) :
        print(' ', end = '')

    #while loop for * and spaces
    x = 1
    while x < 2 * i :
        if x == 1 or x == 2 * i - 1 :
            print('*', end = '')
        else :
            print(' ', end = '')
        x += 1
    print()
Output
  *
 * *
*   *
 * *
  *
Answer

n
=
3
# number of rows
# upper half
for
i
in
range
(
1
,
n
+
1
) :
# for loop for initial spaces
for
j
in
range
(
n
,
i
,
-
1
) :
print
(
' '
,
end
=
''
)
#while loop for * and spaces
x
=
1
while
x
<
2
*
i
:
if
x
==
1
or
x
==
2
*
i
-
1
:
print
(
'*'
,
end
=
''
)
else
:
print
(
' '
,
end
=
''
)
x
+=
1
print
()
# lower half
for
i
in
range
(
n
-
1
,
0
,
-
1
) :
# for loop for initial spaces
for
j
in
range
(
n
,
i
,
-
1
) :
print
(
' '
,
end
=
''
)
#while loop for * and spaces
x
=
1
while
x
<
2
*
i
:
if
x
==
1
or
x
==
2
*
i
-
1
:
print
(
'*'
,
end
=
''
)
else
:
print
(
' '
,
end
=
''
)
x
+=
1
print
()
Output
*
* *
* *
* *
*