Python Program to Print Cross Star Pattern

Introduction

A cross star pattern is formed by stars (*) arranged in a cross shape. The stars are printed along the middle row and the middle column of the pattern. This exercise helps in practicing how to control the placement of stars using loops and conditional logic.

Problem Statement

Create a Python program that:

  • Accepts the size of the pattern (an odd number).
  • Prints a cross-shaped star pattern.

Example:

  • Input: size = 5
  • Output:
    *   *
     * *
      *
     * *
    *   *
    

Solution Steps

  1. Input the Size: The user specifies the size of the cross pattern, which should be an odd number to ensure symmetry.
  2. Use Nested Loops: The outer loop handles the rows, and the inner loop handles printing the stars and spaces.
  3. Conditionally Print Stars: Stars are printed on the middle column and the middle row of each row, while spaces are printed elsewhere.

Python Program

# Step 1: Input the size of the pattern (must be odd)
size = int(input("Enter the size of the cross pattern (odd number): "))

# Step 2: Outer loop for rows
for i in range(size):
    # Step 3: Inner loop for columns
    for j in range(size):
        # Step 4: Print stars for the middle column and diagonal positions
        if i == j or j == size - i - 1:
            print("*", end="")
        else:
            print(" ", end="")
    # Move to the next line after printing each row
    print()

Explanation

Step 1: Input the Size of the Pattern

  • The program starts by asking the user for the size of the cross pattern. The size must be an odd number to ensure symmetry.

Step 2: Outer Loop for Rows

  • The outer loop controls how many rows are printed. It runs from 0 to size - 1.

Step 3: Inner Loop for Columns

  • The inner loop controls how many columns are printed in each row.

Step 4: Conditional Printing of Stars and Spaces

  • Stars (*) are printed in the following positions:
    • On the main diagonal (i == j),
    • On the anti-diagonal (j == size - i - 1).
  • Spaces are printed elsewhere to create the cross shape.

Output Example

For size = 5, the output will be:

*   *
 * *
  *
 * *
*   *

For size = 7, the output will be:

*     *
 *   *
  * *
   *
  * *
 *   *
*     *

Conclusion

This Python program prints a cross star pattern using nested loops and conditional logic. Stars are printed on the diagonals to form the cross shape, while spaces are printed elsewhere. This exercise helps in practicing loop control and conditional statements in Python.

Comments