Skip to main content

Control Flow: Practice

Pyramid Star Pattern

Hi guys ✌️Today we will be practicing pyramid star patterns. If you have gone through the previous article of triangle star pattern questions, you will find these questions easy to approach and you will be able to solve them with ease. The concepts and the approach are similar to that. Also, I assume now we are relatively comfortable with pattern problems. Yes or No?? 😅If it's a No, We know our weapon for these questions( A pen and Paper ).

"Developing the attitude and basic logical aptitude for problem solving really helps in the long run."
Suggestion: Take a pen and a paper while solving these questions and dry run with examples. (Reminder)

Problem 1: Pyramid Star Pattern

Write a java program to print Pyramid star( equilateral triangle ) pattern of N rows.

Input

Input number of rows: 5

Output

    *
   ***
  *****
 *******
*********

Approach

Before you read further have a close look at the above pattern. And note down your observations.

Intuition

Pattern consists of N (for this case 5) rows. Each row contains 2*i-1(where i is the current row number) stars. In addition to stars, the pattern has leading spaces. Each row contains some spaces. To count total spaces per row point your mouse over the above pattern. How many leading spaces are there in each row?? Try to figure that out as we will need to print that number of spaces first then stars.

For N=5 as given the output pattern

Row 1: 4 spaces // N-current row number=?(5-1=4)

Row 2: 3 spaces // N-current row number=?(5-2=3)

Row 3: 2 spaces // N-current row number=?(5-3=2)

Row 4: 1 spaces // N-current row number=?(5-4=1)

Row 5: 0 spaces // N-current row number=?(5-5=0)

N - current row number = Number of spaces in the current row

Now give it a try !!

 Try it out yourself here!

Explanation/Steps
  1. Input number of rows to print from user. Store it in a variable say N.
  2. To iterate through rows, run an outer loop from 1 to N. The loop structure should look like for(i=1; i<=N; i++).
  3. To print spaces, run an inner loop from 1 to N-i. The loop structure should look like for(j=1; j<=N-i; j++). Inside this loop print single space.
  4. To print star, run another inner loop from 1 to 2 * i - 1. The loop structure should look like for(j=1; j<=(2*i - 1); j++). Inside this loop print star.
  5. After printing stars for current row, move to next line i.e. print new line.
Solution
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        // Input total number of rows from the user
        System.out.println("Enter number of rows: ");
        Scanner scanner = new Scanner(System.in);
        int N = scanner.nextInt(); //total rows

        /* Iterate through rows */
        for (int i = 1; i <= N; i++) {
            /* Print leading spaces */
            for (int j = 1; j <= N - i; j++) {
                System.out.print(" ");
            }

            /* Print star */
            for (int j = 1; j <= (2 * i - 1); j++) {
                System.out.print("*");
            }

            /* Move to the next line */
            System.out.println();
        }

        scanner.close();
    }
}

Problem 2: Hollow Pyramid Star Pattern

Write a javav program to print hollow pyramid star pattern (*) pattern of N rows.

Input

Input number of rows: 5

Output

    *
   * *
  *   *
 *     *
*********

Approach

Notice the pattern. What do you think?? Isn't it similar to the pattern of problem 1? This time we just have the border of the pyramid. Help me in defining "border". This time we just have the stars only for first and last row or first and last column of the pattern of problem 1. Can we give it a shot now??

Intution

If you notice carefully, you will find that the logic to print a hollow pyramid is almost similar to the pyramid star pattern(problem 1) logic. Just with this pattern you need to print stars only for the first column, last column, first row and last row.

If we relate to the first problem, in addition to stars, the pattern had leading spaces before the stars in each row. Each row contains some leading spaces. To count the total leading spaces per row point your mouse over the above pattern. How many leading spaces are there in each row?? There are N-i( i is the current row number) leading spaces. (We have already found this in Intuition of problem 1).

Iterate over N rows and first print leading spaces in every row. How will you print leading spaces? Hint: Use a for loop

After printing the leading spaces, now start with the logic to print hollow pyramid. At max, there can be (2*i-1) stars in row. We basically need to print two things "*"(asterisks) and " "(space) now. Think of conditions. When you will print what? Print star for the first column(j==1), first row(i==1), last column(j==2*i-1) or last row(i==N) otherwise print space. Do we need (i==1) compulsorily? No, We can remove that if we want because (j==1) would cater to that condition as well.

Now give it a try !!

Explanation/Steps
  1. Input number of rows to print from user. Store it in a variable say N.
  2. To iterate through rows run an outer loop from 1 to N. The loop structure should look like for(i=1; i<=N; i++).
  3. To print spaces, run an inner loop from 1 to N- i. The loop structure should look like for(j=1; j<=N-i; j++). Inside this loop print single space.
  4. To print star, run another inner loop from 1 to 2*i-1. The loop structure should look like for (j=1; j<=(2*i-1); j++). Inside this loop print star for first column(j==1), first row(i==1), last column(j==2*i-1) or last row(i==N). Otherwise, print space.
  5. After printing all columns of a row, move to next line i.e. print new line.
Solution
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        // Input total number of rows from the user
        System.out.println("Enter number of rows: ");
        Scanner scanner = new Scanner(System.in);
        int N = scanner.nextInt(); //total rows

        for (int i = 1; i <= N; i++) {
            /* Print leading spaces */
            for (int j = 1; j <= N - i; j++) {
                System.out.print(" ");
            }

            /* Print hollow pyramid */
            for (int j = 1; j <= (2 * i - 1); j++) {
                /*
                 * Print star for last row (i==rows),
                 * first column(j==1) and for
                 * last column (j==(2*i-1)).
                 */
                if (i == 1 || i == N || j == 1 || j == (2 * i - 1)) {
                    System.out.print("*");
                } else {
                    System.out.print(" ");
                }
            }

            /* Move to the next line */
            System.out.println();
        }

        scanner.close();
    }
}

Problem 3: Inverted Pyramid Star Pattern

Write a java program to print inverted Pyramid star pattern for N rows.

Input

Input number of rows: 5

Output

*********
 *******
  *****
   ***
    *  

Approach

Have you gone through the first problem?? The pattern of this problem and the first problem are the water images of each other. Notice the pattern carefully. Please give it a try guys without looking at the solution. The approach is similar to problem 1. I am very confident that you will be able to solve it on your own. 🙌

Intuition

Pattern consists of N (for this case 5) rows.

To solve this question, we essentially need to find two things :

1)Relationship between current row number and leading spaces in that row

2)Relationship between current row number and number of stars in that row

Take out your pen and paper and try to find out the above two things.

The pattern consists of leading spaces. Each row contains i – 1 leading space (where i is the current row number).

Each row has exactly 2 * N - (2 * i - 1) stars.

Now give it a try !!

Try it out yourself here!

Explanation/Steps
  1. Input number of rows to print from user. Store it in a variable say N.
  2. To iterate through rows, run an outer loop from 1 to N. The loop structure should look like for(i=1; i<=N; i++).
  3. To print spaces, run an inner loop from 1 to i - 1 . The loop structure should look like for(j=1; j<i; j++). Inside this loop print single space.
  4. To print stars, run another inner loop from 1 to 2 * N - (2 * i - 1). The loop structure should look like for(j=1; j<= (2*N - (2*i-1)); j++). Inside this loop print star.
  5. After printing all stars for each row, move to next line i.e. print new line.
Solution
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        // Input total number of rows from the user
        System.out.println("Enter number of rows: ");
        Scanner scanner = new Scanner(System.in);
        int N = scanner.nextInt(); //total rows

        for (int i = 1; i <= N; i++) {
            /* Print leading spaces */
            for (int j = 1; j < i; j++) {
                System.out.print(" ");
            }

            /* Print stars */
            for (int j = 1; j <= (2 * N - (2 * i - 1)); j++) {
                System.out.print("*");
            }

            /* Move to the next line */
            System.out.println();
        }

        scanner.close();
    }
}

Problem 4: Hollow Inverted Pyramid Star Pattern

Write a java program to print hollow inverted Pyramid star pattern for N rows.

Input

Input number of rows: 5

Output

*********
 *     *
  *   *
   * *
    *

Approach

Notice the pattern. What do you think?? Isn't it similar to the pattern of problem 3? This time we just have the border of the inverted pyramid star pattern. The above pattern is almost similar to the inverted pyramid star pattern(problem 3) with stars printed only for first or last column and for first or last row. Is it getting too difficult ?? 😵‍💫🥹If yes please take a small break and then come back.

Don't you think this is the mix of problem 2(hollow pyramid star pattern) and problem 3( inverted pyramid star pattern)?? Once go through both these problems then Give it a shot !! It will also help you in analysing the understanding of those problems and implementing those concepts.

Intuition

The above pattern is similar to inverted pyramid star pattern with stars printed only for first or last column and for first or last row.(If you remember 🙂 we had a similar condition in problem 2 as well where stars were printed only for first or last column and for first or last row)

We will iterate through N rows. For each row, First, we will print the leading spaces and then we can use logic of hollow pyramid star pattern(problem 2). And then we will get our pattern. Make sense or not?? I hope yes ✌️.

Now please give it a try !! If you get the solution by just reading the intuition. Congratulations 🥳🫡. Otherwise, definitely, we can refer to the solution.

Try it out yourself here!

Explanation/Steps
  1. Input number of rows to print from user. Store it in a variable say N.
  2. To iterate through rows, run an outer loop from 1 to N. The loop structure should look like for(i=1; i<=N; i++).
  3. To print leading spaces, run an inner loop from 1 to i - 1. The loop structure should look like for(j=1; j<i; j++). Inside this loop print single space.
  4. To print stars, run another inner loop from 1 to 2* N - (2 * i - 1). The loop structure should look like for(j=1; j<=(2*N-(2*i-1)); j++).Inside this loop print star for first column(j==1), first row(i==1), last column(j==2*i-1) or last row(i==N). Otherwise, print space.
  5. After printing all columns of a row, move to next line i.e. print new line.
Solution
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        // Input number of rows from the user
        System.out.println("Enter number of rows: ");
        Scanner scanner = new Scanner(System.in);
        int N = scanner.nextInt(); //total rows

        /* Iterate through rows */
        for (int i = 1; i <= N; i++) {
            /* Print leading spaces */
            for (int j = 1; j < i; j++) {
                System.out.print(" ");
            }

            /* Print hollow pyramid */
            for (int j = 1; j <= (2 * N - (2 * i - 1)); j++) {
                /*
                 * Print star for first row(i==1),
                 * last row(i==N)
                 * first column (j==1) and for
                 * last column (rows*2-(2*i-1))
                 */
                if (i == 1 || i == N || j == 1 || j == (2 * N - (2 * i - 1))) {
                    System.out.print("*");
                } else {
                    System.out.print(" ");
                }
            }

            /* Move to the next line */
            System.out.println();
        }

        scanner.close();
    }
}

I guess you must have enjoyed playing around with these questions and there was not much difficulty in understanding if you have used your weapon (a pen and paper XD) and solved questions in previous articles. 😅As suggested at the beginning of the article, dry running with examples make the code and logic more clear.

"Remember Practice leads to Perfection".

Happy Learning !! 😀See you in the next article with more interesting questions.