Published in

Buzz Code

# Java 8 | Pattern Practice 1 — Triangle and Downward Triangle

Hi guys! Welcome to another Java practice with me. Today We’re going to learn how to generate the patterns in Java. These pattern practices will help you to grow your coding skill, and get familiar with the loop. So let’s get this started!

# Question 1. print the pattern like below.

`** ** * ** * * ** * * * *`

To make this triangle you have to find the pattern(haha) which is hiding in it.

This is the hint, there’s a 1 star on the row 1, and 2 stars on the row 2….and so on. So you would need a nested loop for this, one for counting rows, and another one for counting stars. If you don’t know what is the nested loop yet, checkout my old post below.

Now here comes the answer, so let’s solve it before you see!

I set the variable `line` go from 1 to 5, and set the variable `star` starts from 1 as well. And I put the condition as `star<=line` , so it can stop when it gets bigger than the number of the `line` .
So when the `line` is 1, the `star` will be 1 and done, and when the `line` is 2, the `star` will be 1, 2 and done….
And you see I made the first print method as `print()` so it doesn’t change its line, and when the first loop finishes to print the stars, I added the `println()` so it can move on to the next line. I explained the print method on the post below.

# Question 2. Print the pattern like below.

`* * * * ** * * ** * ** **`

On the hint you see there are 5 stars on line 1, 4 stars on line 2, 3 stars on line 3…..Wait, do you see the pattern here? 5+1=6, 4+2=6, 3+3=6… The sum of the number of the stars and its line is all 6! Wow that was a big hint. I hope you can solve this!

That’s right, you can put the condition of the second loop as `star<=(6-line)` ! Then when the `line` is 1, the `star` will go from 1 to 5, and when the `line` is 2 the `star` will go from 1 to 4…

So that’s all for today, wasn’t it fun guys? I can hear you all cheering and giggling because of the excitement:). I will bring you guys more of the pattern practices next time, so stay tuned! See you next time!

--

--

--

Happy coding!

## Student Kim

Learn something new everyday.