×

Pattern Programs in Java

Pattern Programs in Java

In Java, pattern programs are the most important from the perspective of interviews. The pattern programs improve thinking and coding skills. It also helps us to develop a firm grip on looping concepts. In this section, we will create different pattern programs.

We have categorized the pattern programs into the following different categories.

  • Character/ Alphabet Patterns
  • Numeric/ Number Patterns
  • Star Patterns

Character/ Alphabet Patterns

1. Right Triangle Pattern

Filename: RightTrianglePatternExample.java

public class RightTrianglePatternExample{             
public static void main(String[] args)
{
               int firstAlphabet = 65; // ASCII value of the character ‘A’
               int row = 8; //defines number of rows
               //The loop takes care of the row.
               for(int r = 0; r < row; r++)
               {
                               // The loop handles column
                               for(int c = 0; c <= r; c++)
                               {
                                              System.out.print((char)(firstAlphabet) + " ");
                               }                            
                               System.out.println(); // moves the cursor to the next line
               }
}
}

Output:

A

A A

A A A

A A A A

A A A A A

A A A A A A

A A A A A A A

A A A A A A A A

Explanation: Let us understand the working of code. The first two lines written in the main method are straight-forward. We are assigning values to the variables firstAlphabet and row. Now, consider the following code snippet taken from above.

               for(int r = 0; r < row; r++)
               {
                               for(int c = 0; c <= r; c++)
                               {
                                              System.out.print((char)(firstAlphabet) + " ");
                               }                            
                               System.out.println();
               }

In the above-written code snippet, we have two nested for loops. The outer loop deals with the rows and columns are taken care of by the inner loop. The outer loop runs eight times from 0 to 8.

Iteration 1:

For r =0, 0 < 8 (true)
For c =0, 0 <= 0 (true)

Output:

A

The inner loop runs only once, as it starts from zero and ends at 1, and the print-statement of the inner for loop prints the character A. The control now shifts to the println-statement, which prints nothing but forces the cursor to embark on its journey from the next line. The variable r gets incremented by one and gets the value 1.

Iteration 2:

For r =1, 1 < 8 (true)
For c =0, 0 <= 1 (true)

Output:

A
A A

In the second iteration, the inner loop runs two times (from 0 to 1 and from 1 to 2), and print-statement also prints the character A twice. The cursor again jumps to the next line. Finally, the variable r gets incremented by one and gets the value 2.

Iteration 3:

For r =2, 2 < 8 (true)
For c =0, 0 <= 2 (true)

Output:

A
A A
A A A

At this time the inner loop runs three times (0 to 3) and prints the character A thrice. The cursor again moves to the next line, and the variable r gets the value 3.

Iteration 4:

For r =3, 3 < 8 (true)
For c =0, 0 <= 3 (true)

Output:

A
A A
A A A
A A A A

Now, the inner loop executes four times (0 to 4). Hence, we get the character A four times in the fourth row. Again, the cursor shifts to the next line, and the variable r is now 4.

Iteration 5

For r =4, 4 < 8 (true)
For c =0, 0 <= 4 (true)

Output:

A
A A
A A A
A A A A
A A A A A

At this time, we get the character A five times (0 to 5), and the r variable gets the value 5. The cursor is again placed at the next line.

Iteration 6:

For r =5, 5 < 8 (true)
For c =0, 0 <= 5 (true)

Output:

A
A A
A A A
A A A A
A A A A A
A A A A A A

Now the iteration of the inner loop is from 0 to 6, i.e., six times. Therefore, we see six times A. The cursor is again ready to print from the next line. The value of the r variable is 6.

Iteration 7:

For r =6, 6 < 8 (true)
For c =0, 0 <= 6 (true)

Output:

A
A A
A A A
A A A A
A A A A A
A A A A A A
A A A A A A A

Now, we can easily guess why we are getting seven times A. The r variable is now 7.

Iteration 8:

For r =7, 7 < 8 (true)
For c =0, 0 <= 7 (true)

Output:

A
A A
A A A
A A A A
A A A A A
A A A A A A
A A A A A A A
A A A A A A A A

At this time, we get the character A eight times. The r variable gets incremented to 8. In the next iteration, the condition for the r variable evaluates false (8 < 8), and the outer loop terminates, and eventually, the program execution ends.

2. Repeating Right Triangle Pattern

Filename: RepeatingRightTrianglePatternExample.java

public class RepeatingRightTrianglePatternExample
{             
public static void main(String[] argvs)
{
               int firstAlphabet = 65; // 65 is the ASCII value the ‘A’ character
               int row = 8; //defines number of rows
               //the loop takes care of the row
               for(int r = 0; r < row; r++)
               {
                               // the loop handles column
                               for(int c = 0; c <= r; c++)
                               {
                                              System.out.print((char)(firstAlphabet + c) + " ");
                               }                            
                               System.out.println(); // moves the cursor to the next line
               }
}
}

Output:

A
A B
A B C
A B C D
A B C D E
A B C D E F
A B C D E F G
A B C D E F G H

3. Another Repeating Right Triangle Pattern

Filename: RepeatingRightTrianglePatternExample1.java

public class RepeatingRightTrianglePatternExample1
{             
public static void main(String[] argvs)
{
               int firstAlphabet = 65; // 65 is the ASCII value the ‘A’ character
               int row = 8; //defines number of rows
               //The loop takes care of the row.
               for(int r = 0; r < row; r++)
               {
                               // The loop handles column
                               for(int c = 0; c <= r; c++)
                               {
                                              System.out.print((char)(firstAlphabet) + " ");
                               }             
                               firstAlphabet++; 
                               System.out.println(); // moves the cursor to the next line
               }
}
}

Output:

A  
B B
C C C
D D D D
E E E E E
F F F F F F
G G G G G G G

4. Character-Triangle Pattern

Filename: CharacterTrianglePatternExample.java

public class CharacterTrianglePatternExample
{             
public static void main(String[] argvs)
{
               int firstAlphabet = 65; // 65 is the ASCII value the ‘A’ character
               int row = 8; //defines number of rows
               //The loop takes care of the row.
               for(int r = 0; r < row; r++)
               {
                               //The loop deals with the indentation process           
                               for(int indent = row; indent >= r; indent--)
                                              System.out.print(" ");                      
                               // The loop handles column
                               for(int c = 0; c <= r; c++)
                               {
                                              System.out.print((char)(firstAlphabet + c) + " ");
                               }             
                               System.out.println(); // moves the cursor to the next line
               }
}
}

Output:

         A
        A B
       A B C
      A B C D
     A B C D E
    A B C D E F
   A B C D E F G

5. Character-Diamond Pattern

Filename: CharacterTrianglePatternExample.java

public class CharacterTrianglePatternExample
{             
public static void main(String[] argvs)
{
               int firstAlphabet = 65; // 65 is the ASCII value the ‘A’ character
               int row = 8; //defines number of rows
               //The loop takes care of the row.
               for(int r = 0; r < row; r++)
               {
                               //The loop deals with the indentation          
                               for(int indent = row; indent >= r; indent--)
                                              System.out.print(" ");       
                               //character 'A' is printed only once               
                               if(firstAlphabet != 65)       
                                              System.out.print((char)(firstAlphabet));
                               // The loop handles white spaces between characters
                               // in a single row
                               for(int c = -1; c <= 2*r-1; c++)
                               {
                                              System.out.print(" ");
                               }             
                               System.out.print((char)(firstAlphabet));
                               //Moving to the next character
                               ++firstAlphabet;
                               System.out.println(); // moves the cursor to the next line
               }
               //The following section of code prints
               //the second half of the diamond
               //We will be printing character starting from the
               //second last row.
               firstAlphabet-=2;
               for(int r = row - 2; r >= 0; r--)
               {
                               //The loop deals with the indentation process           
                               for(int indent = row; indent >= r; indent--)
                                              System.out.print(" ");       
                               //Again, ‘A’ is printed only once     
                               if(firstAlphabet != 65)       
                                              System.out.print((char)(firstAlphabet));
                               // The loop handles inter-space between characters
                               for(int c = -1; c <= 2*r-1; c++)
                               {
                                              System.out.print(" ");
                               }             
                               System.out.print((char)(firstAlphabet));
                               //Move to the previous character  
                               --firstAlphabet;
                               System.out.println(); // moves the cursor to the next line
               }
}
}

Output:

                        A
                    B     B
                 C           C
               D               D
             E                    E
           F                        F
         G                           G
        H                              H
         G                           G
           F                         F
              E                    E
                D               D
                   C           C
                      B      B
                          A

6. Character Pattern – K Shaped

Filename: KShapedPatternExample.java

public class KShapedPatternExample
{
public static void main(String[] argvs)
{
               int firstAlphabet = 65; // 65 is the ASCII value the ‘A’ character
               int row = 8; //defines number of rows
               //The loop takes care of the row.
               for(int r = 0; r < row; r++)
               {
                               // The loop handles column
                               for(int c = 0; c < row - r; c++)
                               {
                                              System.out.print((char)(firstAlphabet + c) + " ");
                               }                            
                               System.out.println(); // moves the cursor to the next line
               }
               // The section of code prints the second half of the K – shaped pattern
               for(int r = 1; r < row; r++)
               {                            
                               for(int c = 0; c <= r; c++)
                               {
                                              System.out.print((char)(firstAlphabet + c) + " ");
                               }                            
                               System.out.println(); // moves the cursor to the next line
               }
}
}             

Output:

A B C D E F G H
A B C D E F G
A B C D E F
A B C D E
A B C D
A B C
A B
A
A B
A B C
A B C D
A B C D E
A B C D E F
A B C D E F G
A B C D E F G H

Numeric/ Number Patterns

Filename: NumericPatternExample.java

public class NumericPatternExample
{             
public static void main(String[] argvs)
{
               int row = 5;
               int r, c, j; 
               for(r = 0; r < row; r++) //The loop handles rows
               {
                               for(j = 2*(row - r); j >= 0; j--) //Different indentation for different rows
                               {          
                                              System.out.print(" "); // printing space
                               }
                               for(c = 0; c <= r; c++) //  The loop handles columns
                               {      
                                              System.out.print(c + 1 + " "); // Displaying numbers
                               }   
                               System.out.println(); // Forcing line break after each row
               }
}
}

Output:

            1
         1 2
      1 2 3
   1 2 3 4
1 2 3 4 5

Star Patterns

Filename: StarPatternExample.java

public class StarPatternExample
{             
public static void main(String[] argvs)
{
               int row = 5;
               int r, c, j; 
               for(r = 0; r < row; r++) //The loop handles rows
               {
                               for(j = 2*(row - r); j >= 0; j--) //Different indentation for different rows
                               {          
                                              System.out.print(" "); // printing space
                               }
                               for(c = 0; c <= r; c++) //  The loop handles columns
                               {      
                                              System.out.print("* "); // Displaying stars
                               }   
                               System.out.println(); // Forcing line break after each row
               }
}
}

Output:

            *
         * *
      * * *
   * * * *
* * * * *

We will discuss other pattern programs in the coming sections.


Related Topics

Java File Extension

A computer file's suffix is called its file extension. It is easily recognized since it appears immediately after a period (.) in the file name. Consider the file Demo.java as an...

3 minutes read.

Convert list to array Java

One of the popular collection interfaces for storing an ordered collection is the List. The List interface may contain repeating groups and preserves the insertion order of entries. This article will...

4 minutes read.

3N+1 problem program in Java

The 3N+1 problem is a hypothesis in the field of abstract mathematics (not yet proven). Collectively known as the Collatz problem. This tutorial will describe about the 3N+1 problem and...

3 minutes read.

Java Beans

It is a Java class, It follows conventions they are: It must have a no-arg constructorIt must be serializable.It must provide the methods to get and set the properties Uses Of Java...

3 minutes read.

Java Math scalb() Method

The scalb() method of Java Math class returns a single perfectly rounded product of floating-point and member of the double value set as if performed by d*2scaleFacor rounded value. Syntax: public static...

2 minutes read.

Difference Between Java and PHP

The two most used programming languages are PHP and Java. Both of them have a lot of similarities and distinctions. Let's first grasp each of them individually before examining their...

3 minutes read.

Java Anon Proxy

The Java Anon Proxy (JAP), also known as JonDonym, is a proxy system designed to enable Web browsing with revocable (the use of or publication under a pseudonym, a false...

4 minutes read.

Java 8 Features

Java 8 Features: After the great success of Java 7, many developers were waiting for the next version of one of the best languages in the tech world. Moreover, on...

6 minutes read.

Java Program to Print Permutations of String

A string is given and you need to print all the possible ways for that string. Permutation is arranging the characters of a string to get outputs from the given...

3 minutes read.

Convert List to String in Java

We occasionally need to create a string from a list of characters. Since a string is only a collection of characters, a character array can be converted into a string....

6 minutes read.

How to achieve Multiple Inheritance in Java

Multiple Inheritance is the type of inheritance where one class inherits the properties of more than one super class. For example, class Child inherits (extends) the classes Father and Mother....

4 minutes read.

public static void main string args meaning in java

In java main() method is the initial point for execution of the program. If a program doesn’t contain the main method, the program will not execute. JVM(java virtual machine) starts...

3 minutes read.

Banking Application in Java

JDBC (Java Database Connectivity), which provides an API to connect to, execute, and fetch data from any databases, can be used to handle transactions in Java. There are several factors...

7 minutes read.

Vigesimal in Java

A number system with a base of 20 is known as the vigesimal in Java. A base-20 (base-score) numeric system, often known as a vigesimal system, is centered on the twenty...

4 minutes read.

Non-primitive data types in Java

The kind of data stored in the variable is determined by its type. The type describes the data category (different sizes and values). These are not already built into the devices....

4 minutes read.

Java program to find frequency of characters in a string

In this article, you will understand the how to find the frequency of characters in strings by using Java programming language. Along with this, you will understand the hashing concept...

3 minutes read.

Java TreeMap

TreeMap in Java with Example Java TreeMap implements the NavigableMap interface. It extends Map Interface. Java TreeMap is based on the red-black Tree implementation. It stores the key-value pair in sorted...

7 minutes read.

Print Pencil Shape Pattern in Java

Another pattern made from asterisk symbols that use loops and other logical concepts is the pencil pattern. It is usually requested to draw a pattern using a program. To write the...

6 minutes read.

Binary Search Java

Binary search is a search mechanism for key elements from the given List/Array. In Binary search, the search mechanism is followed by dividing the array into parts; hence the search...

3 minutes read.

How to Read XML Files in Java?

Introduction Today, we are going to learn about how to read XML files in java. Before, reading the XML Files let us learn about XML. XML Files The full form of XML is...

8 minutes read.