0% found this document useful (0 votes)
20 views13 pages

Java Patterns: Stars, Numbers & Shapes

Uploaded by

kingamaan460
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views13 pages

Java Patterns: Stars, Numbers & Shapes

Uploaded by

kingamaan460
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1 — Butterfly Pattern

Input: n = 4
Output:
* *
** **
*** ***
********
*** ***
** **
* *

public class Butterfly {


public static void main(String[] args) {
int n = 4;
// Upper half
for (int i = 1; i <= n; i++) {
// left stars
for (int j = 1; j <= i; j++) [Link]("*");
// spaces
for (int j = 1; j <= 2*(n - i); j++) [Link](" ");
// right stars
for (int j = 1; j <= i; j++) [Link]("*");
[Link]();
}
// Lower half
for (int i = n; i >= 1; i--) {
for (int j = 1; j <= i; j++) [Link]("*");
for (int j = 1; j <= 2*(n - i); j++) [Link](" ");
for (int j = 1; j <= i; j++) [Link]("*");
[Link]();
}
}
}

2 — Concentric Rectangular Number Pattern (Square of numbers)


Input: n = 4 (produces 7×7)
Output:
4444444
4333334
4322234
4321234
4322234
4333334
4444444

public class ConcentricRectangular {


public static void main(String[] args) {
int n = 4;
int size = 2*n - 1;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
int top = i;
int left = j;
int right = size - 1 - j;
int bottom = size - 1 - i;
int val = [Link]([Link](top, bottom), [Link](left, right));
[Link]((n - val) + (j == size-1 ? "" : " "));
}
[Link]();
}
}
}
3 — Zig-Zag Star Pattern (3-row zigzag)
Input: n = 15 (number of columns)
Output:
* * *
******
* * * *

public class ZigZag {


public static void main(String[] args) {
int n = 15; // number of positions
int rows = 3;
char[][] a = new char[rows][n];
// fill with spaces
for (int i=0;i<rows;i++) for (int j=0;j<n;j++) a[i][j] = ' ';
int row = 0; int dir = 1;
for (int col = 0; col < n; col++) {
a[row][col] = '*';
if (row == 0) dir = 1;
else if (row == rows-1) dir = -1;
row += dir;
}
// print
for (int i = 0; i < rows; i++) {
for (int j = 0; j < n; j++) [Link](a[i][j]);
[Link]();
}
}
}
4 — Hollow Diamond (even/odd safe)
Input: n = 5 (height/top half)
Output:
*
**
* *
* *
* *
* *
* *
**
*

public class HollowDiamond {


public static void main(String[] args) {
int n = 5; // rows in top half
// upper including middle
for (int i = 1; i <= n; i++) {
for (int s = i; s < n; s++) [Link](" ");
if (i == 1) [Link]("*");
else {
[Link]("*");
for (int sp = 1; sp <= 2*i - 3; sp++) [Link](" ");
[Link]("*");
}
}
// lower
for (int i = n - 1; i >= 1; i--) {
for (int s = i; s < n; s++) [Link](" ");
if (i == 1) [Link]("*");
else {
[Link]("*");
for (int sp = 1; sp <= 2*i - 3; sp++) [Link](" ");
[Link]("*");
}
}
}
}

5 — Hourglass Number Pattern


Input: n = 5
Output:
123454321
1234321
12321
121
1
121
12321
1234321
123454321

Solution (Java):
public class HourglassNumber {
public static void main(String[] args) {
int n = 5;
// upper including middle
for (int i = 0; i < n; i++) {
for (int s = 0; s < i; s++) [Link](" ");
for (int k = 1; k <= n - i; k++) [Link](k);
for (int k = n - i - 1; k >= 1; k--) [Link](k);
[Link]();
}
// lower
for (int i = n - 2; i >= 0; i--) {
for (int s = 0; s < i; s++) [Link](" ");
for (int k = 1; k <= n - i; k++) [Link](k);
for (int k = n - i - 1; k >= 1; k--) [Link](k);
[Link]();
}
}
}

6 — Hollow Square with Diagonals (general n)


Input: n = 7
Output:
*******
** **
****
* * *
****
** **
*******
Solution (Java):
public class HollowSquareDiagonals {
public static void main(String[] args) {
int n = 7;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 || j == 0 || i == n-1 || j == n-1 || i==j || i+j==n-1) [Link]("*");
else [Link](" ");
}
[Link]();
}
}
}

7 — Mirror Number Pyramid with Spaces


Input: n = 6
Output:
1
212
32123
4321234
543212345
65432123456

public class MirrorNumberPyramid {


public static void main(String[] args) {
int n = 6;
for (int i = 1; i <= n; i++) {
for (int sp = i; sp < n; sp++) [Link](" "); // two spaces for alignment
for (int k = i; k >= 1; k--) [Link](k + " ");
for (int k = 2; k <= i; k++) [Link](k + (k==i ? "" : " "));
[Link]();
}
}
}
8 — Numeric Diamond (incremental counter)
Input: n = 4
Output:
1
23
456
7 8 9 10
456
23
1

public class NumericDiamond {


public static void main(String[] args) {
int n = 4;
int counter = 1;
// top
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) [Link]((counter++) + (j==i? "" : " "));
[Link]();
}
// bottom
for (int i = n - 1; i >= 1; i--) {
for (int j = 1; j <= i; j++) [Link]((counter - (i*(i+1)/2)) + (j==i? "" : " "));
// adjust counter to next sequence start
counter = counter - (i*(i+1)/2);
// advance counter to reflect printed numbers
for (int j = 1; j <= i; j++) counter++;
[Link]();
}
}
}
9 — Floyd’s Triangle but Right-Aligned (wide numbers)
Input: n = 6
Output:
1
23
456
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21

public class FloydRightAlign {


public static void main(String[] args) {
int n = 6;
int count = 1;
// compute width for alignment (length of last number)
int maxNum = n*(n+1)/2;
int width = [Link](maxNum).length() + 1; // +1 for a trailing space
for (int i = 1; i <= n; i++) {
// left padding
int pad = (n - i) * width;
for (int p = 0; p < pad; p++) [Link](" ");
for (int j = 1; j <= i; j++) {
String s = [Link](count++);
// pad each number to width (right aligned)
[Link](" ".repeat(width - [Link]()) + s);
}
[Link]();
}
}
}
10 — Star Hourglass (solid)
Input: n = 5
Output:
*********
*******
*****
***
*
***
*****
*******
*********

public class StarHourglass {


public static void main(String[] args) {
int n = 5;
// top including middle
for (int i = 0; i < n; i++) {
for (int s = 0; s < i; s++) [Link](" ");
for (int k = 0; k < 2*(n - i) - 1; k++) [Link]("*");
[Link]();
}
// bottom
for (int i = 2; i <= n; i++) {
for (int s = 0; s < n - i; s++) [Link](" ");
for (int k = 0; k < 2*i - 1; k++) [Link]("*");
[Link]();
}
}
}
11 — Square Number Spiral (clockwise) — small size demo
Input: n = 4
Output:
1234
12 13 14 5
11 16 15 6
10 9 8 7

public class NumberSpiral {


public static void main(String[] args) {
int n = 4;
int[][] a = new int[n][n];
int top = 0, bottom = n-1, left = 0, right = n-1;
int num = 1;
while (true) {
if (left > right) break;
for (int j = left; j <= right; j++) a[top][j] = num++;
top++;
if (top > bottom) break;
for (int i = top; i <= bottom; i++) a[i][right] = num++;
right--;
if (left > right) break;
for (int j = right; j >= left; j--) a[bottom][j] = num++;
bottom--;
if (top > bottom) break;
for (int i = bottom; i >= top; i--) a[i][left] = num++;
left++;
}
for (int i=0;i<n;i++){
for (int j=0;j<n;j++) [Link](a[i][j] + (j==n-1? "" : " "));
[Link]();
}
}
}

12 — Triangle of Prime Flags (mark primes with *)


Input: n = 7 (print first n numbers in triangle form)
Output (n=7 triangle):
2
35
7 11 13
17 19 23 29
31 37 41 43 47
53 59 61 67 71 73
79 83 89 97 101 103 107

public class PrimeTriangle {


public static boolean isPrime(int x) {
if (x < 2) return false;
for (int i = 2; i*i <= x; i++) if (x % i == 0) return false;
return true;
}
public static void main(String[] args) {
int rows = 7;
int count = 0;
int num = 2;
for (int r = 1; r <= rows; r++) {
int printed = 0;
while (printed < r) {
if (isPrime(num)) {
[Link](num + (printed == r-1 ? "" : " "));
printed++;
}
num++;
}
[Link]();
}
}
}

Common questions

Powered by AI

In Floyd's Triangle Right-Aligned, the `width` variable ensures numeric alignment across rows by calculating it as the number of digits in the maximum expected number (`maxNum`). This value includes extra space allowances to assure text-based alignment remains consistent till the last number. Each number printed is adjusted rightwards by padding it with spaces to attain this computed width. By using this consistent overriding width, numbers align neatly on the right, irrespective of their digit count .

The Numeric Diamond pattern uses a counter to continuously increment numbers till the middle row reaches its maximum, resetting sequentially in the lower half based on a calculated decrement. The lower half substracts from the counter by computing the reduction value required to set back the sequence appropriately for each row's start, maintaining distinct continuity. This incremental and corrective alternating approach allows for seamless numeric flow across top and bottom sections of the diamond, ensuring precise continuation of the sequence .

The zigzag pattern is generated using a two-dimensional array to map stars and spaces over three rows for `n` columns. The logic involves iterating over columns and placing a star in a current row, which changes based on direction. Initially, direction is downward (increased row number), and upon reaching the last row, the direction reverses. This results in a visible zigzag motion as the stars are placed accordingly on their path across the columns .

The hollow diamond pattern maintains balance for both even and odd `n` by structuring iterations that separately handle the upper (including middle) and lower halves of the diamond. The pattern starts with leading spaces, adjusting by increment or decrement for each level, and adds stars with spaces in between for lower levels of each half, creating uniform sections irrespective of the total height. The specific condition checks for even/odd values ensure single star placements correctly appear at the topmost and bottom-most sections, maintaining the overall symmetry and structure .

The algorithm for generating the Concentric Rectangular Number Pattern calculates the pattern size as `2*n - 1` and iterates over each coordinate in this size. For any coordinate `(i, j)`, it determines the nearest boundary by calculating the minimum distance to any of the four edges of the matrix: top, bottom, left, and right. This minimum value (`val`) represents the 'layer' of numbers, and it is subtracted from `n` to determine the number to be printed. This approach ensures each layer around the matrix has decrementing numbers as layers progress inwards .

The Mirror Number Pyramid achieves alignment using spaces for leading adjustment. In each row `i`, spaces are printed decreasingly (`i` to `n`), allowing numbers to have a shifted placement. This aligns the edges each time, creating the pyramid shape. Additionally, numbers are first decreased to 1 from the current `i`, then counter-increased back to `i`, filling a pyramid row. The use of consistent space decreases and exact number increments ensures both left and right sides of numbers appear equidistant from each edge, visually structuring the pyramid .

The program evaluates a set of conditions for each position `(i, j)` in an `n x n` grid: if a position lies on any border `(i == 0 || j == 0 || i == n-1 || j == n-1)` or on the primary diagonal `(i == j)` or secondary diagonal `(i + j == n - 1)`, it prints a star. Otherwise, it prints a space. This approach effectively outlines the square and prints stars along its diagonals inside the square, creating a symmetric and visually distinct pattern .

The hourglass number pattern exhibits symmetry through its vertically mirrored structure. In both halves, numbers increment sequentially from 1 up to a peak determined by `n`, then decrement back to 1. Multiple loops manage spaces and numbers: in the upper half, numbers decrease, spaces increase with each row; in the lower half, the process reverses—spaces decrease, and numbers mirror the structure upwards again. This design ensures the top and bottom halves mirror each other perfectly around the central maximal point .

The order of these conditions is crucial as they serve as guards to exit the loop when the spiral formation reaches the center or when boundaries overlap, indicating that all elements in the matrix have been filled. The checks `(left > right)` and `(top > bottom)` ensure the loop exits before attempting to access array indices that would have otherwise exceeded bounds, thereby preventing logic errors and ensuring the spiral completes only once perfectly around the matrix grid .

The butterfly pattern's upper half involves increasing the number of stars from 1 up to a peak at `n`, interspersed with spaces which decrease as the rows progress to maintain symmetry. This pattern is mirrored in the lower half, where the stars start decreasing, maintaining the same symmetry of spaces. The transition from upper to lower half is smooth, as the bottom of the upper half and the top of the lower half maintain a similar number of stars and spaces, ensuring a continuous symmetrical flow .

You might also like