JavaScript Program to Print Star Pattern in X Shape

Introduction

An X-shaped star pattern consists of stars (*) arranged in a cross-diagonal pattern where stars are placed on both the main and secondary diagonals. This pattern is great for practicing loops and conditional logic in JavaScript.

Problem Statement

Create a JavaScript program that:

  • Accepts the size of the pattern (must be an odd number to ensure symmetry).
  • Prints a star pattern in the shape of an 'X'.

Example:

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

Solution Steps

  1. Input the Size of the Pattern: The user specifies the size of the X 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 main diagonal (i == j) and the secondary diagonal (i + j == size - 1), while spaces are printed elsewhere.

JavaScript Program

// Step 1: Input the size of the X pattern (must be odd)
let size = parseInt(prompt("Enter the size of the X pattern (odd number): "));

// Step 2: Outer loop for rows
for (let i = 0; i < size; i++) {
    let output = '';
    
    // Step 3: Inner loop for columns
    for (let j = 0; j < size; j++) {
        // Step 4: Print stars on the diagonals
        if (i === j || i + j === size - 1) {
            output += '*';
        } else {
            output += ' ';
        }
    }
    
    // Print the output for the current row
    console.log(output);
}

Explanation

Step 1: Input the Size of the Pattern

  • The program asks the user for the size of the X pattern, which must be an odd number to create symmetry. The input is converted to an integer using parseInt().

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 at the following positions:
    • On the main diagonal (i === j),
    • On the secondary diagonal (i + j === size - 1).
  • Spaces are printed elsewhere to create the X shape.

Output Example

For size = 5, the output will be:

*   *
 * *
  *
 * *
*   *

For size = 7, the output will be:

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

Conclusion

This JavaScript program prints an X-shaped star pattern using nested loops and conditional logic. Stars are printed on both the main and secondary diagonals, while spaces are printed in the other positions, creating the X shape. This exercise is useful for practicing loop control and conditional logic in JavaScript.

Comments