×

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

How to Convert Hexadecimal to Decimal in Java

How to Convert Hexadecimal to Decimal in Java There are two methods to convert Hexadecimal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method It is a static method of...

2 minutes read.

Java Math atan() Method

The atan() method of Math class computes the trigonometric Arc Tangent (inverse of tangent ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double atan(double a) Parameters: The...

2 minutes read.

Java Float Keyword

Float: In general, there are two categories of data types: primitive data types and non-primitive data types. So, float is the data type which is a primitive data type. Declarating the variables and...

3 minutes read.

Java Imageio

The javax.imageio package contains the final class known as Java ImageIO. For easy image reading, writing, and simple encoding and decoding, the class offers a convenient way. The class offers...

4 minutes read.

nth Prime Number in Java

A number is considered prime if only divisible by one and itself. Prime numbers include, for example, 2, 3, 5, 7, 11, etc. In looking at it another way, a...

5 minutes read.

How to take Array Input in Java

In this tutorial, we will learn about how to take array input in Java. So, before taking inputs let us know what an array is first. Array: An array is a collection...

10 minutes read.

Java Boolean equals() method

The equals() method of Java Boolean class returns a Boolean value true if the specified argument is not null and is same as this object, else it returns false. Syntax public boolean...

2 minutes read.

Stone Game in Java

In this tutorial, we will learn to design a stone game in Java. First of all, we will understand what is this game all about. We will grasp it through...

9 minutes read.

Java For Loop

A for loop is used to execute a set of statements for a fixed number of times. It takes the following form: for (initialization; condition; update) { statements; } The for loop defines...

2 minutes read.

How to Convert Decimal to Octal in Java

How to Convert Decimal to Octal in Java There are two methods to convert Decimal to Octal: Using toOcatlString() method Using user-defined logic Using Integer.toOctalString() method The toOctalString() is astaticmethod of the Integer...

2 minutes read.

Java Math sqrt() Method

The sqrt() method of Java Math class returns the accurately rounded positive square root of the specified double value. Syntax: public static double sqrt(double a) Parameters: The parameter ‘a’ represents the number whose square...

2 minutes read.

Number Pattern Programs in Java

Number Pattern Programs in Java: Number pattern programs are part of pattern programs. In the previous section, we have learned the approach to print the pattern program in Java. To...

6 minutes read.

Java Delete File

There are two techniques to erase a record in Java: Utilizing File.delete() technique.Utilizing File.deleteOnExit() technique. Using File.delete() technique: In Java, we can erase a document by utilizing the File.delete() technique for File class....

2 minutes read.

Java Array Generic

Creating Generic Array in Java A collection of comparable sorts of data is kept in an array. In Java, making a generic array is challenging. The type information of an array's...

4 minutes read.

Java Instanceof Keyword

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). The type of comparison in java differentiates the...

4 minutes read.

Stack vs Heap in Java

In Java, whenever we declare an object or create a variable, whether it is an instance variable, local variable, or static variable, a certain memory is used to store the...

4 minutes read.

India Map Pattern in Java

India Map Pattern is the pattern we'll code now using Java, as demonstrated. We will use a star in Java to print our India map.The specialty is that we will only...

4 minutes read.

Swapping Program in Java

Swapping Program in Java The swapping program in Java is used to interchange the values of the two variables. For example, if X = 12 and Y = 24, then the...

4 minutes read.

MVC in Java

A well-known design pattern is Model-View-Controller. The discipline of web development. We can organize our code in this manner. The document stipulates that a program or application must include a...

4 minutes read.

How to Convert String to Date in Java

How to Convert String to Date in java You can convert String to Date in Java by using the parse() method. There are two classes which have parse() method namely, DateFormat and SimpleDateFormat classes....

2 minutes read.