Java Pattern Programs
Java Pattern Programs
Explanation: This code creates a right-aligned triangle pattern with stars using Java's String.repeat() function.
Program:
int n = 5;
for (int i = 1; i <= n; i++) {
System.out.println(" ".repeat(n - i) + "*".repeat(i * 2 - 1));
}
Output:
***
*****
*******
*********
Explanation: This example centers each row of asterisks in a triangle shape using String.format() to add padding.
Program:
int n = 5;
for (int i = 1; i <= n; i++) {
System.out.println(String.format("%" + (n - i) + "s", "").replace(" ", " ") + "*".repeat(i * 2
- 1));
}
Output:
***
*****
*******
*********
3. Diamond Pattern Using Math.abs()
Explanation: This code generates a diamond pattern with a center alignment using spaces and Math.abs() for symmetry.
Program:
int n = 5;
for (int i = -n + 1; i < n; i++) {
System.out.println(" ".repeat(Math.abs(i)) + "*".repeat(2 * (n - Math.abs(i)) - 1));
}
Output:
***
*****
*******
*********
*******
*****
***
Explanation: This code generates a sequence of powers of 2, showing values from 2^0 up to 2^(n-1).
Program:
int n = 5;
for (int i = 0; i < n; i++) {
System.out.println((int)Math.pow(2, i));
}
Output:
2
4
16
Explanation: This program separates stars with commas and increases the count on each row, creating a visually
distinct pattern.
Program:
int n = 5;
for (int i = 1; i <= n; i++) {
System.out.println(String.join(",", "*".repeat(i).split("")));
}
Output:
*,*
*,*,*
*,*,*,*
*,*,*,*,*
Explanation: This code builds a right-angle triangle by adding an extra * on each new row using a StringBuilder for
int n = 5;
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= n; i++) {
sb.append("*");
System.out.println(sb);
}
Output:
*
**
***
****
*****
Here are a few examples of repeated patterns such as squares or rectangular patterns made using nested loops.
Square Pattern
Program:
int n = 5;
for (int i = 0; i < n; i++) {
System.out.println("*".repeat(n));
}
Output:
*****
*****
*****
*****
*****
Output:
*****
*****
*****