Python Program for Cross or X Pattern

1. Introduction

Creating patterns with programming is a fantastic way to learn about loops and conditional statements. The cross or X pattern is a simple yet visually appealing design that displays two diagonal lines crossing each other to form an 'X'. This tutorial will walk you through writing a Python program to print a cross pattern, which is a great exercise for beginners to get comfortable with Python's basic concepts.

2. Program Steps

1. Ask the user to enter the size of the cross pattern.

2. Use nested loops to iterate over each position in a square matrix.

3. Use a conditional statement within the loop to determine whether to print a star (*) to form the cross pattern or a space for the empty parts.

3. Code Program

# User input for the size of the cross
size = int(input("Enter the size of the cross: "))

# Loop through each position in the square matrix
for i in range(size):
    for j in range(size):
        # Check for diagonal positions
        if i == j or i + j == size - 1:
            print("*", end="")
        else:
            print(" ", end="")
    print()  # New line after each row

Output:

Enter the size of the cross: 5
*   *
 * *
  *
 * *
*   *

Explanation:

1. The program begins by asking the user for the size of the cross pattern. This size will determine the dimensions of the square matrix in which the cross is formed.

2. It then enters a nested loop, where the outer loop iterates over each row, and the inner loop iterates over each column of the matrix.

3. Within the inner loop, a conditional statement checks if the current position is on one of the diagonals of the square matrix. The diagonals are identified by the conditions i == j (for the primary diagonal) and i + j == size - 1 (for the secondary diagonal).

4. If the current position is on a diagonal, a star (*) is printed. Otherwise, a space is printed, creating the empty parts of the pattern.

5. The end="" argument in the print function keeps the output on the same line, only moving to the next line after completing a row, thanks to the print() call outside the inner loop.

6. This approach of using nested loops and conditional statements to print characters based on their position creates a cross pattern, demonstrating basic Python syntax and logic.


Comments