how to print a pattern in Java

8/3/2022
All Articles

Java beginner pattern programs

how to print a pattern in Java

How to Print a Pattern in Java: A Comprehensive Guide

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:

  • Star Pattern
  • Number Pattern
  • Character Pattern

This guide will walk you through an example of printing a star pattern in Java.

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:

  • One star in the first line.
  • Three stars in the second line.
  • Five stars in the third line.

Java Program to Print a Star Pattern

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();
        }
    }
}

Output of the Program

* -
** -
*** -
**** -
***** -
****** -

Understanding the Code

  • The outer loop controls the number of rows.
  • The inner loop prints stars and inserts a hyphen (-) after an odd number of stars.
  • The condition if (j == i * 2) ensures that hyphens are placed correctly.

Other Java Pattern Programs

1. Number Pattern Example

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

2. Character Pattern Example

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

Conclusion

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!

Article