Basic Incrementing Squared Number-Star Pattern
Understanding the Problem
The goal is to print a squared number-star pattern where numbers increment from left to right, separated by '*'.
Pattern Explanation
The pattern follows a grid structure where numbers increase sequentially row-wise.
1*2*3*4
5*6*7*8
9*10*11*12
13*14*15*16
Observations:
- The pattern consists of 4 rows and 4 columns.
- Numbers increment from left to right.
- Each number is followed by a '*', except the last number in each row.
Algorithm
The pattern follows these steps:
- Initialize a number counter starting from 1.
- Loop through rows (from 1 to N).
- Within each row, loop through columns.
- Print the number followed by '*' except for the last number in the row.
- Increment the number after each print.
- Move to the next line after each row.
Method 1: Using Nested Loops
This method uses two loops to print the pattern.
public class NumberPattern {
public static void printPattern(int n) {
int num = 1;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
System.out.print(num++);
if (j < n) System.out.print("*");
}
System.out.println();
}
}
public static void main(String[] args) {
int size = 4;
printPattern(size);
}
}
Output:
1*2*3*4
5*6*7*8
9*10*11*12
13*14*15*16