Tuesday, April 4, 2023

Python program that uses nested loops to print a pattern of stars

# Printing a pattern of stars

rows = 5

for i in range(rows):

    for j in range(i+1):

        print("*", end="")

    print()

Output:

*

**

***

****

*****

This program uses two nested loops to print a pattern of stars. The outer loop iterates over the number of rows we want to print (in this case, 5), while the inner loop iterates over each column in the current row. The inner loop uses the current value of i to determine how many stars to print in that row (starting with 1 star in the first row, 2 stars in the second row, and so on). The end="" argument to the print() function is used to prevent the output from starting a new line after each row of stars is printed.

You can modify this program to print different patterns of stars by changing the values in the loops. For example, to print a pyramid of stars with a base of 9 stars, you can use the following code:

# Printing a pyramid of stars

rows = 5

for i in range(rows):

    for j in range(rows-i-1):

        print(" ", end="")

    for k in range(2*i+1):

        print("*", end="")

    print()

Output:

    *

   ***

  *****

 *******

*********

This program uses the same basic structure as the previous example, but with two inner loops that print spaces and stars in a specific pattern to create a pyramid shape. The first inner loop prints a number of spaces equal to the current row number minus one (starting with 4 spaces in the first row), while the second inner loop prints a number of stars equal to twice the current row number plus one (starting with 1 star in the first row).

No comments:

Post a Comment

Apeejay Surrendra Park Hotels IPO: Should You Invest Today?

The Apeejay Surrendra Park Hotels (ASPH) IPO hits the market today, February 5th, 2024, offering a chance to invest in a well-established...