Skip to main content

Control Flow: Practice

Miscellaneous Star Pattern

If you have gone through the previous articles, I can confidently say that now we are ready to solve most of the problems of star patterns. We have covered various approaches and techniques required to solve these problems. In this article, we will do mixed problems.

Now, Let's start with the questions with our weapon. (A pen and paper)

Problem 1: Diamond Star Pattern

Write a Java program to print diamond star pattern for 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. Try to solve it on your own as we covered the concept in previous articles.

Intuition

The given pattern is a combination of pyramid star pattern and inverted pyramid star pattern. It consists of 2*N-1 rows (for this case N=5). Each row contains spaces and stars printed in increasing and decreasing order.

Stars are printed in increasing order till the Nth row. After Nth row stars are printed in decreasing order.

Spaces are printed in decreasing order till the Nth row. After the Nth row spaces are printed in increasing order. Point your mouse cursor over the pattern to count total spaces.

Now give it a try guys we have already solved various problems on similar lines in previous articles. I am very confident you will be able to solve it.

Try it yourself here!

Explanation/Steps

  1. Input number of rows to print from user (in real number of rows/2). Store it in a variable say N.
  2. Declare two variables to keep track of total columns to print each row, say stars=1 and spaces=N-1.
  3. To iterate through rows, run an outer loop from 1 to 2*N-1. The loop structure should look like for(i=1; i<2*N; i++).
  4. To print spaces, run an inner loop from 1 to spaces. The loop structure should look like for(j=1; j<=spaces; j++). Inside this loop print single space.
  5. To print stars, run another inner loop from 1 to 2*stars-1. The loop structure should look like for(j=1; j<=stars; j++). Inside this loop print star.
  6. After printing all columns of a row, move to next line i.e. print new line.
  7. Check if(i < rows) then increment stars and decrement spaces. Otherwise increment spaces and decrement stars.
Solution
import java.util.Scanner;

public class PyramidPattern {
    public static void main(String[] args) {
        int i, j, N;
        int stars, spaces;

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

        stars = 1;
        spaces = N - 1;

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

            /* Print stars */
            for (j = 1; j < stars * 2; j++)
                System.out.print("*");

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

            if (i < N) {
                spaces--;
                stars++;
            } else {
                spaces++;
                stars--;
            }
        }
    }
}

Problem 2: Right Arrow Star Pattern

Write a Java program to print right arrow star pattern.

Input

Input number of rows: 5

Output

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

Approach

Notice the pattern. What do you think?? Try to break down the pattern into further patterns and then try to approach the question. This pattern is a combination of two patterns hence, let’s first divide it into two parts.

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

Part 1

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

Part 2

Intuition

This pattern is a combination of two patterns. We will be solving both the parts separately.

If we remove leading spaces, then the upper part star pattern is similar to inverted right triangle star pattern and bottom part to simple right triangle star pattern which we have already covered in previous articles.

For upper pattern,

For N=5

Row 1: 0 spaces // 2*current row number-2=?(2*1-2=0)

Row 2: 2 spaces // 2*current row number-2=?(2*2-2=2)

Row 3: 4 spaces // 2*current row number-2=?(2*3-2=4)

Row 4: 6 spaces // 2*current row number-2=?(2*4-2=6)

Total number of leading spaces in upper part is 2*i – 2. ( where i is current row number)

For lower pattern,

For N=5

Row 1: 8 spaces // 2*N-2*current row number=?(2*5-2*1=8)

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

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

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

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

Total number of leading spaces in lower part is 2*N – 2*i. ( where i is current row number)

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 for upper part, 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 2*i-2. The loop structure should look like for(j=1; j<=(2*i-2); j++). Inside this loop print single space.
  4. To print star, run another 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.
  5. After printing stars for current row, move to next line i.e. print new line.
  6. Now to iterate through rows for lower part, run an outer loop from 1 to N. The loop structure should look like for(i=1; i<=N; i++).
  7. To print spaces, run an inner loop from 1 to (2*N - 2*i). The loop structure should look like for(j=1; j<=(2*N - 2*i); j++). Inside this loop print single space.
  8. To print star, run another inner loop from 1 to i. The loop structure should look like for(j=1; j<=i; j++). Inside this loop print star.
  9. After printing stars for current row, move to next line i.e. print new line.
Solution
import java.util.Scanner;

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

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

        // Print the upper part of the arrow
        for (i = 1; i < N; i++) {
            // Print leading (2 * rownumber - 2) spaces
            for (j = 1; j <= (2 * i - 2); j++) {
                System.out.print(" ");
            }

            // Print inverted right triangle star pattern
            for (j = 1; j <= N - i + 1; j++) {
                System.out.print("*");
            }

            System.out.println();
        }

        // Print lower part of the arrow
        for (i = 1; i <= N; i++) {
            // Print leading (2 * N - 2 * rownumber) spaces
            for (j = 1; j <= (2 * N - 2 * i); j++) {
                System.out.print(" ");
            }

            // Print simple right triangle star pattern
            for (j = 1; j <= i; j++) {
                System.out.print("*");
            }

            System.out.println();
        }
    }
}

Problem 3: Plus Sign Pattern

Write a Java program to print plus sign pattern.

Input

Input number of rows: 5

Output

    +
    +
    +
    +
+++++++++
    +
    +
    +
    +

Approach

Notice the pattern. What do you think?? Note down your observations and then try to solve the problem.

Intuition

  1. The pattern consists of 2 * N - 1 rows.
  2. When you look to the centre horizontal plus line i.e. +++++++++ this line. It also consists of 2 * N - 1 columns.
  3. For every other row, single plus symbol is printed after N - 1 blank spaces.

Now give it a shot !! It's not a difficult one.

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 2 * N - 1. The loop structure should look like for(i=1; i<=(2 * N - 1); i++).
  3. To print centre horizontal plus if(i==N), run a inner for loop inside if condition from 1 to 2 * N - 1. The loop structure should look like for(j=1; j<=(2 * N - 1); j++). Inside this loop print plus sign.
  4. To print spaces before single plus sign, run another loop inside the else condition from 1 to N - 1. The loop structure should look like for(j=1; j<=N-1; j++). Inside this loop print single space. After the loop ends, print a single plus sign.
  5. After printing all plus sign for each row, move to next line i.e. print new line.
Solution
import java.util.Scanner;

public class PlusPattern {
    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();

        // Run an outer loop from 1 to 2 * N - 1
        for (i = 1; i <= (2 * N - 1); i++) {
            // For the center horizontal plus
            if (i == N) {
                for (j = 1; j <= (2 * N - 1); j++) {
                    System.out.print("+");
                }
            } else {
                // For spaces before a single plus sign
                for (j = 1; j <= N - 1; j++) {
                    System.out.print(" ");
                }
                System.out.print("+");
            }

            System.out.println();
        }
    }
}

Problem 4: Cross Star Pattern

Write a Java program to print cross star pattern.

Input

Input number of rows: 5

Output

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

Approach

Notice the pattern carefully. We have done enough number of questions. Can we give it a honest try without looking at the solution?

Intuition

Essentially in the given pattern, there are two diagonals crossing each other.

The pattern consists of exactly 2 * N - 1 rows and 2 * N - 1 columns. Each row contains exactly 2 * N - 1 columns.

Can you notice that stars are printed for the below two cases, otherwise print space?

  • For the first diagonal, when row and column numbers both are equal.
  • For the second diagonal, stars are printed if column number == 2 * N- row number.

Try it yourself here!

Explanation/Steps

  1. The pattern consists of exactly 2 * N - 1 rows and 2 * N - 1 columns. Hence run an outer loop to iterate through rows with structure for(i=1; i<= 2 * N - 1; i++).
  2. Since each row contains exactly 2 * N - 1 columns. Therefore, run inner loop as for(j=1; j<=2 * N - 1; j++).
  3. Inside this loop, you can notice that stars are printed for the below two cases, otherwise print space.
    • For the first diagonal i.e. when row and column numbers both are equal. Print star if(i == j).
    • For the second diagonal, stars are printed if(j == 2 * N - i).
Solution
import java.util.Scanner;

public class XPattern {
    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 <= 2 * N - 1; i++) {
            for (j = 1; j <= 2 * N - 1; j++) {
                if (j == i || (j == 2 * N - i)) {
                    System.out.print("*");
                } else {
                    System.out.print(" ");
                }
            }

            System.out.println();
        }
    }
}

Problem 5: 8 Star Pattern

Write a Java program to print 8 star pattern of N rows.

Input

Input number of columns: 5

Output

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

Approach

Tired?? Take a break and then come back with a fresh mind.

Are we ready now? Notice the pattern carefully, this question is more about observation. Try to do it on your own at least give it a fair try.

Intuition

Take into account the below three things and we are good to go.

  • Print a hollow square star pattern with N columns and 2*N- 1 rows.
  • Modify hollow square pattern logic(We have already done this problem guys). Instead of star, print space at top and bottom corners and in the center intersection edge.
  • Finally, modify hollow square logic to print star instead of space for the Nth row.

Try it yourself here!

Explanation/Steps

  1. Input number of columns to print from user. Store it in a variable say N.
  2. Iterate through (N*2)-1 rows. Run an outer loop with structure for(i=1; i<N*2; i++).
  3. Iterate through N columns. Run an inner loop with structure for(j=1; j<=N; j++).
  4. Inside the inner loop first check conditions for corner and center intersection spaces. Print space for:
    1st row and 1st or Nth column i.e. if(i==1 && (j==1 || j==N))
    Nth row and 1st or Nth column i.e. if(i==N && (j==1 || j==N))
    N*2-1 row and 1st or Nth column i.e. if(i==N*2-1 && (j==1 || j==N))
  5. Print stars for 1st row or 1st column i.e. if(i==1 || j==1), Nth row or Nth column i.e. if(i==N || j==N), N*2-1th row i.e. if(i==N*2-1).
  6. Otherwise, print spaces if the above conditions do not match.
Solution
import java.util.Scanner;

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

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

        for (i = 1; i < N * 2; i++) {
            for (j = 1; j <= N; j++) {
                // Condition for corner and center intersection space
                if ((i == 1 && (j == 1 || j == N)) ||
                        (i == N && (j == 1 || j == N)) ||
                        (i == N * 2 - 1 && (j == 1 || j == N))) {
                    System.out.print(" ");
                } else if (i == 1 || i == N || i == (N * 2) - 1 || j == 1 || j == N) {
                    System.out.print("*");
                } else {
                    System.out.print(" ");
                }
            }

            System.out.println();
        }
    }
}

Happy Learning!

See you in the next article with more interesting concepts.