×

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 Arrays

An array is an object that stores a collection of values. An array can store two types of collection data: objects and primitives. An array is a collection of values which...

2 minutes read.

Stable Marriage Problem in Java

Given N men and N women, the Stable Marriage Problem asks you to match up the men and women in such a way that there are never any two people...

6 minutes read.

ArrayDeque in Java

ArrayDeque The ArrayDeque is one of the essential concepts in java to implement the deque interface. It will allow us to apply a resizable array to implement the Deque interface. This...

8 minutes read.

Automorphic Number Program in Java

We will learn about automorphic numbers through examples in this article, and we'll also make Java programmes that can determine whether a specific number was automorphic or not. What is an...

3 minutes read.

Java String vs StringBuffer

Java String vs StringBuffer In this section, we will discuss the key differences between String and StringBuffer class. Before moving to the ahead in this section, let’s introduce with both classes. String...

4 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.

Java Database Connectivity with MySQL

In this tutorial, we will learn how to connect Database with MySQL in Java. 5 Steps to Connect to the Database in Java Load the driver (or) Register the driver classEstablish a...

4 minutes read.

Client Server Program in Java

Client Server Program in Java The client and server are the two main components of socket programming. The client is a computer/node that request for the service and the server is...

7 minutes read.

How to use Lambda Expression in Java?

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single method interface using an...

4 minutes read.

Java Output Formatting

Sometimes we want a program's output to be displayed in a specific format. The printf () function in the C programming language can be used to achieve this. We will...

4 minutes read.

Java OCR

In this article, you will be acknowledged about what is a tesseract OCR, how it works, what are its used and advantages and disadvantages. Also, you will be able to...

4 minutes read.

Normal and Trace of a Matrix in Java

Normal of a matrix The square root of the total squares of each element in a matrix is known as the matrix's normal. Think of the following matrix as an example. Example: [[1,2,3]  ...

3 minutes read.

Thread Scheduler in java

Scheduling: it is defined as the execution of multiple threads on a single CPU in some order is called scheduling. Preemptive-priority scheduling: This algorithm schedules threads based on their priority relative to other...

11 minutes read.

Menu Driven Program in Java

Menu Driven Program in Java The menu-driven program in Java is a program that displays a menu and then takes input from the user to choose an option from the displayed...

3 minutes read.

Dangling Else problem in Java

A language interpretation uncertainty is the hanging other issue. The following two types of condition executed code are both possible in programming: 1. if-then-else form 2. if-then form When dealing with the nested...

3 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.

Why main method is static in Java

The method serves as the entry point for Java programmes or simply the point from which the programme begins to run. As a result, it is one of the most...

4 minutes read.

Java Constant

A constant is an unchangeable entity in coding, as its title implies. The value which cannot be altered, in other terms. We shall understand about Java constants and exactly how...

3 minutes read.

Level order Traversal of a Binary Tree in Java

In Java, a level order traversal of a tree structure is also referred to as the breadth-first traversal of the binary tree. Regarding the subsequent binary tree: Level order traversal is as...

5 minutes read.

Sorting Algorithms in Java

Sorting Algorithms in Java Sorting is the technique that puts the elements of an array or list either in descending or ascending order. For example, take an array A, whose elements...

3 minutes read.