Introduction
An X-shaped star pattern is a symmetrical arrangement of stars (*
) in the shape of the letter 'X'. The stars are printed diagonally from the top-left to the bottom-right and from the top-right to the bottom-left. This exercise is great for practicing nested loops and conditional logic in Python.
Problem Statement
Create a Python program that:
- Accepts the size of the pattern (an odd number).
- Prints a star (
*
) pattern in the shape of an 'X'.
Example:
- Input:
size = 5
- Output:
* * * * * * * * *
Solution Steps
- Input the Size: The user specifies the size of the X pattern, which should be an odd number to ensure symmetry.
- Use Nested Loops: The outer loop handles the rows, and the inner loop handles printing the stars and spaces.
- Conditionally Print Stars: Print stars on the diagonals (positions where the row and column indices match or add up to
size - 1
).
Python Program
# Step 1: Input the size of the pattern (must be odd)
size = int(input("Enter the size of the X 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 at diagonal positions
if i == j or i + j == size - 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 X pattern. The size must be an odd number to create symmetry.
Step 2: Outer Loop for Rows
- The outer loop controls how many rows are printed. It runs from
0
tosize - 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 at the diagonal positions:- On the main diagonal (
i == j
), - On the anti-diagonal (
i + j == size - 1
).
- On the main diagonal (
- Spaces are printed elsewhere to form the X shape.
Output Example
For size = 5
, the output will be:
* *
* *
*
* *
* *
For size = 7
, the output will be:
* *
* *
* *
*
* *
* *
* *
Conclusion
This Python program prints a star pattern in the shape of an X using nested loops and conditional logic. Stars are printed on the diagonals, while spaces are printed elsewhere to create the X shape. This exercise helps in practicing loop control, conditional statements, and formatting output in Python.
Comments
Post a Comment
Leave Comment