Skip to main content

Control Flow: Practice

Triangle Star Pattern

Have you gone through the square and rhombus star pattern article? If yes, then I think we have a fair enough idea about how to approach the pattern problems. These questions are more like playing games. Solving the triangle pattern problems will help us in approaching pyramid pattern problems which in turn builds the logic for diamond pattern problems and much more.

Suggestion: Take a pen and a paper while solving these questions and dry run with examples. Dry running examples helps a lot in these type of problems. You will catch the error instantly if you dry run and you can even understand the solution in a much better way.

Problem 1: Right Triangle Star Pattern

Write a Java program to print right triangle star pattern (*) pattern of N rows.

Input

Input number of rows: 5

Output

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

Approach

Look at the pattern for some time. What is coming to your mind?

Intuition

If you look at the pattern carefully you will find that stars are in increasing order of rows.

Row 1: *

Row 2:**

Row 3:***

Row 4:****

Row 5:*****

Noticed something?? Number of stars in a row is same as current row number.

Ask yourself: Iterate through N rows, and for each row how many columns will you iterate?

Hint: Iterate through N rows, and for each row iterate for i ( i is current row number) columns.

Now give it a try !!

Try it 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 with loop structure for(i=1; i<=N; i++).
  3. To iterate through columns run an inner loop from 1 to i with loop structure for(j=1; j<=i; j++). Inside the inner loop print star.
  4. After printing all columns of a row move to next line i.e. print new line.
Solution
import java.util.Scanner;

public class PatternStars {
    public static void main(String[] args) {
        int i, j, N; // i --> rows, j --> columns, N --> total rows

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

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

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

Problem 2: Hollow Right Triangle Star Pattern

Write a Java program to print hollow right triangle 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 triangle. 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. Are we on the same page??

Intuition

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

If we relate to the first problem, we can say that we will need two for loops. One outer loop to iterate over each row and one inner loop to iterate over each column(The inner loop iterates for i times where i is current row number). But this time there will be some changes in inner loop as the star is printed only for specific cases(star is printed only for first or last column or for first or last row).

We basically need to print two things "*"(asterisks) and " "(space). Think of conditions. When you will print what? Print star for first column(j==1), first row(i==1), last column(j==i) 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. Why condition for last column is j==i ??Dry run on an example and you are good to go.

Now give it a try !!

Try it 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 iterate through columns, run an inner loop from 1 to i. The loop structure should look like for(j=1; j<=i; j++).
  4. Inside inner loop print star for first or last column or first or last row( first column(j==1), first row(i==1),last column(j==i) 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 PatternStarsWithBorder {
    public static void main(String[] args) {
        int i, j, N; // i --> rows, j --> columns, N --> total rows

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

        // Iterate through N rows
        for (i = 1; i <= N; i++) {

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

            System.out.println();
        }
    }
}

Problem 3: Mirrored Right Triangle Star Pattern

Write a Java program to print mirrored right triangle star pattern (*) pattern of 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 mirror images of each other. Notice the pattern carefully. We just need to find the relationship between row number and number of spaces in that row. Please give it a try without looking at the solution. I am very confident that you will be able to arrive at the solution.

Intuition

Have a close look at the pattern. Place your mouse cursor on to the pattern, to count spaces. Try to decode the logic of given pattern. We only need to change the logic of printing spaces with the existing logic of the right triangle star pattern(1st problem). How many 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 yourself here!

Explanation/Steps

  1. Input number of rows to print from user. Store it in some variable say N.
  2. To iterate through rows run an inner 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 with loop structure for(j=1;j<=N-i;j++). Inside this loop print single space.
  4. To print stars run another inner loop from 1 to i, with loop structure for(j=1; j<=i; j++).
  5. After printing all columns of a row, move to next line i.e. print new line.
Solution
import java.util.Scanner;

public class PatternStarsInvertedTriangle {
    public static void main(String[] args) {
        int i, j, N; // i --> rows, j --> columns, N --> total rows

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

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

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

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

Problem 4: Hollow Mirrored Right Triangle Star Pattern

Write a Java program to print hollow mirrored right triangle 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 3? This time we just have the border of the mirrored right triangle star pattern. The above pattern is almost similar to mirrored right triangle star pattern(problem 3) with stars printed only for first or last column and for first or last row. Is it getting difficult ??😵‍💫🥹If yes please take a small break.

Don't you think this is the mix of problem 2(hollow right triangle star pattern) and problem 3(mirrored right triangle star pattern)?? Once go through both these problems then Give it a shot!

Intuition

The above pattern is similar to mirrored right triangle 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 right triangle 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 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 inner loop from 1 to N with structure 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 the loop print single space.
  4. To print star, run another inner loop from 1 to i with loop structure for(j=1; j<=i; j++). Inside the loop print star for first or last column or first or last row.
  5. After printing all columns move to next line.
Solution
import java.util.Scanner;

public class HollowRightTriangle {
    public static void main(String[] args) {
        int i, j, N; // i --> rows, j --> columns, N --> total rows

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

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

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

            System.out.println();
        }
    }
}

Problem 5: Inverted Right Triangle Star Pattern

Write a Java program to print inverted right triangle star pattern (*) pattern of N rows.

Input

Input number of rows: 5

Output

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

Approach

This will be our last question for this exercise. I am confident this question will be a piece of cake for you if you have gone through the above questions. Can we correlate this problem with problem 1?? Try it once without looking at the solution🙂

Intuition

If you look at the pattern carefully you will find that stars are in increasing order of rows.

For N=5(where N is the total number of rows or input)

Row 1 : ***** -> N stars = N-1+1 stars

Row 2 :**** ->N-1 stars = N-2+1 stars

Row 3 :*** ->N-2 stars = N-3+1 stars

Row 4 :** ->N-3 stars = N-4+1 stars

Row 5 :* ->N-4 stars = N-5+1 stars

Noticed something? Number of stars in a row = N - current row number +1.

Ask yourself: Iterate through N rows, and for each row how many columns will you iterate?

Hint: Iterate through N rows, and for each row iterate for N-i+1 columns(i is current row number).

Now give it a try !!

Try it yourself here!

Explanation/Steps

The above pattern contains N rows and each row contains N-i +1 columns (where i is the current row number).

  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 iterate through columns run an inner loop from 1 to N-i+1 . The loop structure should look like for(j=1; j<=N-i+1; j++). Inside this loop print star.
  4. After printing all columns of a row, move to next line i.e. print new line.
Solution
import java.util.Scanner;

public class InvertedTriangleStars {
    public static void main(String[] args) {
        int i, j, N; // i --> rows, j --> columns, N --> total rows

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

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

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

Happy Learning!😀

See you in the next article with more interesting questions.