Buzz Code
Published in

Buzz Code

Java 8 | Pattern Practice 2 — Downward Triangle 2, Pyramid

Hi guys! It was the Christmas yesterday, I couldn’t post any because of that! I hope you all had a great family time. And today, let’s get back on the pattern practice! Last time we did the triangle and the downward triangle. It was a such a fun practice(I hope you guys feel the same:)). If you missed it you can always checkout my last post!

And today we’re going to generate different patterns and it’s gonna be bit more complicated than the last one. Ok, now let’s get this started!

[Downward Triangle 2 — Odd Numbers Only]

So what do we want to make is this.

*****
***
*

This one is tricky, but as always try to solve it by yourself first. it doesn’t need to be the perfect answer, it’s all about developing your problem solving process.

Hmm…I don’t really see the pattern here…What if I change the numbers of the rows like below?

I know, it still seems like there’s no pattern, but you can do this! Let’s think until the brain hurts. There is an answer below.

If I double the number of each row, it will be 6 for the row 3, 4 for the row 2 and 2 for the row 1.

So the number of the stars on each line is 1 smaller than the doubled number of the row! So we can write the code like below.

[Pyramid]

0000*
000***
00*****
0*******

I put the “0” on the pattern so you can see the error easily when it occurs, you can put the space instead. You can solve this only with the for statement, but then there will be too many nested loops, so let’s try to use the If statement as well.

I visualized the patterns into numbers. And first let’s focus on the last numbers of each line. It’s 5,6,7,8. So we can easily get those numbers by adding 4 on the numbers of each row.

Okay, we’re half way there! Now we should figure out how to put zeros. Do you see what I see? 1,2,3,4 and 4,3,2,1…Yes! The zeros are (5-row). So I can change the code into

This! But wait…If the zeros were 4,3,2,1….What if we set the rows into 4,3,2,1 as well?

Than the last numbers of the each line are (9-row), and the zeros are the numbers of each row! Wow than the code would be like below.

I put space instead of the zero this time. And the code got simpler.

So These is all for today guys. Some of you might solved them differently, still if you could get the patterns right, that can be an answer too. But the thing is there are better ones among those answers. It’d be nice when you focus on using less For and If statements for running the program efficiently. Thank you for reading guys! See ya!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store