Incrementing + Inverted Squared Number-Star (Alternate Type 3)

Understanding the Problem

The goal is to print an alternate inverted squared number-star pattern where row order alternates in a different way.

Pattern Explanation

The pattern follows a grid structure where numbers increase sequentially, but certain rows are positioned differently.

1*2*3*4
9*10*11*12
17*18*19*20
13*14*15*16
5*6*7*8
            

Observations:

  • The pattern consists of 5 rows and 4 columns.
  • Numbers increment from left to right across the grid.
  • Each number is followed by a '*', except the last number in each row.
  • Rows are arranged in a specific order, where the third row has the highest numbers.

Algorithm

The pattern follows these steps:

  1. Initialize a number counter starting from 1.
  2. Store values in a 2D array as they increment.
  3. Rearrange row positions based on the required output order.
  4. Within each row, print numbers left to right with '*'.
  5. Move to the next line after printing each row.

Method 1: Using Nested Loops

This method first stores values in an array and then prints them in the required alternating order.

public class NumberPattern {
    public static void printPattern(int n) {
        int[][] arr = new int[n][n];
        int num = 1;
        
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                arr[i][j] = num++;
            }
        }
        
        int[] order = {0, 2, 4, 3, 1}; // Custom row order for printing
        
        for (int i = 0; i < n; i++) {
            int row = order[i];
            for (int j = 0; j < n; j++) {
                System.out.print(arr[row][j]);
                if (j < n - 1) System.out.print("*");
            }
            System.out.println();
        }
    }
    
    public static void main(String[] args) {
        int size = 5;
        printPattern(size);
    }
}
            

Output:

1*2*3*4
9*10*11*12
17*18*19*20
13*14*15*16
5*6*7*8