how to print a pattern in Java
Java beginner pattern programs
Pattern printing in Java is an essential concept that helps beginners understand loops and nested loops. In Java, pattern programs are generally categorized into three main types:
This guide will walk you through an example of printing a star pattern in Java.
Below is a Java program that prints a star pattern where hyphens are added after an odd number of stars in each line. The pattern follows this sequence:
public class Main {
public static void main(String[] args) {
// Loop through rows
for (int i = 0; i < 6; i++) {
for (int j = 0; j <= 11; j++) {
System.out.print("*");
if (j == i * 2) {
System.out.print(" - ");
}
}
System.out.println();
}
}
}
* -
** -
*** -
**** -
***** -
****** -
-
) after an odd number of stars.if (j == i * 2)
ensures that hyphens are placed correctly.public class NumberPattern {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
public class CharPattern {
public static void main(String[] args) {
for (char i = 'A'; i <= 'E'; i++) {
for (char j = 'A'; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
Output:
A
A B
A B C
A B C D
A B C D E
Pattern printing in Java is a great way to practice loops and conditionals. By understanding the logic behind star, number, and character patterns, you can strengthen your Java programming skills. Try modifying the code to experiment with different patterns!