202k views
5 votes
Write a nested loop that prints the following output.

1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1

1 Answer

3 votes

Answer:

Written in Python:

rows = 8

for i in range(1,rows+1):

for j in range(1,rows):

print(" ")

x = 1

for j in range(1,i):

print(str(x)+" ",end='')

x = int(x*2)

while x >= 1:

print(str(x)+" ",end='')

x = int(x/2)

Step-by-step explanation:

For each row, the print out is divided into two parts.

1. Starts from 1 and ascends to a peak

2. Then descends from the peak to 1

This line initializes the number of rows to 0

rows = 8

This iterates from 1 to the number of rows

for i in range(1,rows+1):

This prints a blank at the end of sequence printed on each line

for j in range(1,rows):

print(" ")

This initializes each row element to 1

x = 1

This iterates the number of item to print on each line depending on the row

for j in range(1,i):

This prints the row element in ascending order to the peak

print(str(x)+" ",end='')

This calculates the next element to be printed

x = int(x*2)

This checks for valid row element to print in descending order to 1

while x >= 1:

print(str(x)+" ",end='')

x = int(x/2)

User Dyno Cris
by
4.9k points