java-star-hash-program

Here we are going to show you how you can draw a pattern with stars (*) and hashes (#). If you know how to draw a triangle star pattern, you can directly skip to the end of the post.

So what we are going to print is this pattern –

Logic behind the code

  1. At first, we are printing a sing row with four stars in it.
This will print four stars or a single row with four stars.

2. Repeat the row four times.

This will give us an output like this –

3. Print a new line after every four stars or after the inner loop.

Now it looks like this –

4. Make it look like a triangle. The logic is, we are going to print stars only if ‘i’ is less than or equals to ‘j’. Remember, here ‘i’ is the reason for stars and ‘j’ is the reason for rows. In short i==column and j==row. So what I mean to say is, print stars only if the column is less than or equal to row. When there is only one row, the number of columns should be one. When there are two rows, the number of columns should be two.

If you run the above code, you will get the output like this –

Our 99% work is done. Now just put ‘else’ part and print hashes ‘#’.

Complete code of the program –

Code –

Output

If you have any doubt or any kind of question, please do comment in the comment section. If you have any suggestion regarding our explanation or code please let us know in the comment section or contact us.

Program to print rectangle pattern with star and hashes – Java
Tagged on:

Leave a Reply

Your email address will not be published. Required fields are marked *