×

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 Integer rotateRight() method

The rotateRight() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value right by the specified number of bits. Syntax public...

1 minute read.

Volatile keyword in Java

Multiple threads can change a variable's value by using the volatile keyword. Making classes thread-safe is another application for it. It indicates that using a method or an instance of...

3 minutes read.

Root exception in java

Java: The main feature of java which is not in C or object oriented programming language is platform independence. Not only the platform independence there are many other features in java...

3 minutes read.

String to JSON in Java

Nowadays, receiving data in JSON String format rather than XML is quite frequent. Java does not transform JSON String to JSON Object when dealing with JSON String. However, using the...

3 minutes read.

Thread Program in Java

Thread Program in Java Thread program in Java is the continuation of multithreading program in Java. In this topic, we will learn about the usage of threads, race condition in multithreading,...

8 minutes read.

Java Boolean logicalXor() Method

The logicalXor() method of Java Boolean class returns the result of implementing logical XOR operation on the specified Boolean operands. Syntax: public static boolean logicalXor (boolean a, boolean b) Parameters: The parameters ‘a’ and...

2 minutes read.

Selection Sort in Java

Selection Sort in Java Selection sort is also a simple sorting algorithm that works by repeatedly finding the minimum element from the unsorted portion of the input array, and placing it...

5 minutes read.

Java Map Generic

Java arrays maintain an ordered collection of things, and the index can be used to access the data (an integer). Unlike HashMap, which stores data as a Key/Value pair. We...

3 minutes read.

Java Interface Lock

A synchronisation method called the Lock interface is available as of JDK 1.5. It is comparable to a synchronised block but more complex and versatile. The package java.util.concurrent contains the...

4 minutes read.

How to Change the Day in the Date using Java?

To operate with the date and time in Java, we need the Calendar abstract class. It provides a number of helpful interfaces that enable us to convert dates between a...

4 minutes read.

Hybrid Inheritance in Java

The most crucial OOPs concept in Java is inheritance, which enables the transfer of a class's properties to another class. It describes the Is-A relationship generally. We can create a...

3 minutes read.

Abstract classes in Java

Abstract classes in Java Java uses the 'abstract’ keyword to make a class abstract. Such classes are known as abstract classes, and the process is known as abstraction. In programming language, abstract...

4 minutes read.

Java SE vs EE

Java : Java is an independent platform. It works on any kind of operating system. We use java to develop and to focus on large or major projects. The goal of...

3 minutes read.

Java 8 Multimap

Java comes with several practical built-in collection libraries. However, there are situations when we need specialized collections that are not included in the Java standard library. The Multimap is one...

7 minutes read.

Access Modifier in Java

The access modifiers in java are used to change the accessibility and scope of a method, constructor, class, and fields. If you are aware of C++ language, when we declare any member...

2 minutes read.

Java Math IEEEremainder() Method

The IEEEremainder() method of Math class calculates the remainder as prescribed by the IEEE754 standard. This method simply returns the remainder when f1 (dividend) is divided by f2 (divisor). Syntax: public static...

2 minutes read.

Java exception list

Java uses exceptions, like the majority of contemporary programming languages, to deal with both errors and "extraordinary events." When an exception arises inside the program, it messes up the regular...

6 minutes read.

Java Generate UUID

What java Generate UUID? A 128-bit long value that is universally unique serves as the basis for the terms UUID (Universally Unique Identifier) and GUID (Globally Unique Identifier). Hexadecimal (octet) digits...

5 minutes read.

Java String equalsIgnoreCase() method

equalsIgnoreCase() method compares two Strings based on the their content but ignore the case. Syntax public boolean equalsIgnoreCase(Objects anObject) Parameter anObject: Object to be compared with the current String without case consideration. Returns It returns true...

1 minute read.

Java Math round() Method

The round() method of Java Math class returns a long or an int value that is closest to the argument and is rounded to positive infinity. Syntax: public static int round(float a)public...

2 minutes read.