Write a Java Code To Create Pyramid and Pattern

In Java, creating patterns and pyramids is a common programming exercise that can help you improve your problem-solving skills.

Here, we will walk you through creating a pyramid and pattern in Java using loops and conditional statements.


Pyramid Pattern

To create a pyramid pattern, we can use nested loops.

The outer loop will control the number of rows, while the inner loop will control the number of asterisks printed in each row.

public class Pyramid {
    public static void main(String[] args) {
        int rows = 5;

        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= rows - i; j++) {
                System.out.print(" ");
            }
            for (int k = 1; k <= i; k++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

The first loop initializes the i variable to 1 and increments it by 1 until it reaches the value of rows.

In each iteration, the second loop prints the required number of spaces, and the third loop prints the required number of asterisks.

Pattern Printing

We can create various patterns using loops and conditional statements.

Here is an example of a pattern that prints numbers in an inverted triangle shape:

public class Pattern {
    public static void main(String[] args) {
        int rows = 5;

        for (int i = rows; i >= 1; i--) {
            for (int j = i; j <= rows; j++) {
                System.out.print(j + " ");
            }
            System.out.println();
        }
    }
}

In this example, the outer loop initializes the i variable to rows and decrements it by 1 until it reaches the value of 1.

The inner loop prints the required number of numbers in each row.


Conclusion

Creating patterns and pyramids in Java is a great way to improve your programming skills.

By using loops and conditional statements, you can create a wide range of patterns and shapes.

The examples we provided above are just a starting point, and you can experiment with different patterns by modifying the loops and conditions.