Java Program to Print a Cross (X) Pattern

1. Introduction

This blog post will guide you through creating a Java program that prints a cross (X) pattern on the screen, with the size of the cross determined by user input. This program is a great way to practice using loops and conditional statements in Java, as it involves printing characters in specific positions to form the cross shape.

2. Program Steps

1. Import the Scanner class to read the size of the cross from the user.

2. Prompt the user to enter the size of the cross.

3. Use nested loops to print the cross pattern: one loop for rows and another for columns within each row.

4. Inside the loops, use conditional statements to determine when to print an asterisk (*) to form the cross.

5. Compile and execute the program, input the size of the cross, and observe the pattern.

3. Code Program

import java.util.Scanner; // Import Scanner class

public class CrossPattern {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in); // Create Scanner object
        System.out.print("Enter the size of the cross: "); // Prompt for user input
        int size = scanner.nextInt(); // Read the size of the cross from user

        for(int i = 1; i <= size; i++) { // Loop for each row
            for(int j = 1; j <= size; j++) { // Loop for each column
                if(i == j || j == (size - i + 1)) { // Check for cross pattern positions
                    System.out.print("*"); // Print asterisk for the cross
                } else {
                    System.out.print(" "); // Print space elsewhere
                }
            }
            System.out.println(); // New line after each row
        }
        scanner.close(); // Close the scanner
    }
}

Output:

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

Explanation:

1. The program begins by importing the Scanner class to take the size of the cross as input from the user. This size determines the dimensions of the cross pattern.

2. After reading the user's input for the size, the program enters a for loop that iterates over each row of the pattern.

3. Within each row, another for loop iterates over each column. Conditional statements inside this loop check if the current position should have an asterisk (*) to form part of the cross. This is true for positions where the row number equals the column number (i == j) or the column number equals the size of the cross minus the row number plus one (j == (size - i + 1)).

4. If the condition is met, an asterisk is printed; otherwise, a space is printed. This creates the cross pattern, with asterisks forming the diagonal lines of the cross and spaces everywhere else.

5. After completing the inner loop for a row, a newline character is printed to move to the next row, and this process continues until the entire cross is printed.

6. Finally, the Scanner object is closed to prevent resource leaks, adhering to good programming practices.

Comments