×

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 Database Connectivity with Oracle

JDBC: A Programmer can develop a complete application using the Java built-in API’s. So, for storing the data required for solving a real-world problem is stored into a database. To connect...

5 minutes read.

Short Circuit Logical Operators in Java

When there are two or more relational expressions in a decision-making statement, logical operators are utilized to combine them. The logical operators short circuit and not-short circuit fall into two...

5 minutes read.

How to Split String by Comma in Java

strsplit() technique permits you to break a string given the explicit Java string delimiter. The Java string split property is frequently a space or a comma(,) that you want to...

7 minutes read.

Zygodromes in Java

Zygodrome is a positive number created by the same digits running non-trivially. A number is called a zygodrome if identical digits constantly occur together (in pairs). The Greek word "zyg"...

4 minutes read.

Java Math log10() Method

The log10() method of Math class returns the base 10 logarithmic value for the specified double argument. Syntax: public static double log10(double a) Parameters: The parameter ‘a’ represents a double value. Return Value: The log10() method...

2 minutes read.

Program to Find the Common Elements between two Arrays in Java

In this article, we are going to learn how to find the common elements between two arrays using Java. Here, we use different approaches in Java to find the common...

3 minutes read.

Loose Coupling in Java

Loosely coupling mechanism in java means one reference of a variable capable of holding multiple implementation class memory is called loosely coupling. Or in other words, one interface reference variable...

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

How to Create Immutable Classes in Java

Introduction Java is a programming language that is entirely object-oriented, and everything in it is seen as an object. And the blueprint or template of these objects are classes. Several classes...

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.

Java Boolean compareTo() method

The compareTo() method of Java Boolean class compares the Boolean argument with the Boolean instance and returns integer value, zero, or negative 1, or positive 1 based on the result...

2 minutes read.

Difference Between Access Specifiers and Modifiers in Java

Java employs access modifiers to restrict a class's data members, member functions, and constructor. Access modifiers are essential when creating Java program and applications. Access modifiers in Java include: defaultpublicprotectedprivate Default Access Modifiers Without...

4 minutes read.

Sliding Window Problem in Java

A sliding window is used in computer science and data science to process large datasets. It involves breaking the dataset into smaller chunks or windows and then processing it in...

6 minutes read.

Java extend multiple classes

In Java, what does extend mean? One of several Java inheritance keywords is extended, meaning we pass all or most of the Parent class's characteristics through to the Child class. The...

3 minutes read.

HashMap Vs HashTable

HashMap HashMap is the basic implementation of the map interface in Java. HashMap stores the data in key and value pairs. Keys are used to access the value of the element. It...

5 minutes read.

Equilibrium Index of an Array in Java

An array's equilibrium index is the condition where the sum of items with lower and higher indices equals. For example, an array A=[-4,5 2,6,-5] where: a[0]=-4, a[1]=5, a[2]=2, a[3]=6, a[4]=-5 Now according...

4 minutes read.

Lazy Propagation in Segment Tree in Java

The topic of segment trees in Java is continued by the topic of sluggish propagation in segment trees. It is suggested that readers first read through the section tree topic....

4 minutes read.

How to set timer in Java

In this article, you will be very well equipped with the knowledge to set timer in java. The timer in java can be set by using timer class provided by...

3 minutes read.

Java HashMap

Java HashMap extends AbstractMap and implements Map interface. It is the collection of multiple entries where an entry consists of key and value pair. The HashMap can contain only one...

7 minutes read.

Java Math incrementExact() Method

The incrementExact() method of Math class returns the argument incremented by one, throwing an exception if the result overflows an int or a long. Syntax: public static int incrementExact (int a)public static...

1 minute read.