Hi Ivan:
Well as you can probably tell you've solved it the quicker more efficient
way but probably not the better way (depending upon one's definition of
better.) You can imagine how it would be to write an 80-row version or if
having completed it the "boss" says "oh but the user gets to choose the
characters to use did I forget to tell you that?"
I can post the code but you should try it first. Don't think of this as
asterisks and spaces it's all about a pattern and that requires an
algorithm. Roedy pointed out the pattern you should be trying to solve.
Notice one thing however that the right digit is always the same as the left
digit. That means you only need to solve for the number of stars and 1/2
the number of spaces.
I wrote it so a maximum number of rows plus two characters can be set and it
generates the pattern. The only restriction is that the maximum rows must
be odd which is the only way you can get one star in the middle. I did use
nested loops but they don't look nested since I put the second loop into
it's own procedure so I didn't have to repeat it 3 times.
I noticed your code earlier and your comment about getting the "top-half" to
work. Avoid thinking about it as having two parts. I recommend an
iterative process so make sure you can print <n> rows of <n> stars. Then
make it print the same <n> rows but printing <n1> spaces (I think you should
use periods though, you can see them better) plus <n2> stars plus <n1>
spaces.
So you would get something like this:
....*****...
....*****...
....*****...
....*****...
....*****...
It will be working but clearly it's just a square. So now the algorithm
comes down to "how do increase the number of periods and reduce the number
of stars (until there is one star) and then reverse the process"?
Tom
Oliver Wong said:
Ivan said:
hhm..
Okay.. This is what I have so far..
import java.io.*;
import java.math.*;
public class Pattern
{
public static void main( String args[] )
throws IOException
{
int y=1;
int x=1;
int z=1;
int gap = 4;
int size=9;
for (x=1; x<=size; x+=2)
{
for (z=1; z<=gap; z++)
{
System.out.print(" ");
}
for (y=1; (y<=(x)); y++)
System.out.print("*");
System.out.println();
gap--;
}
}
}
i've made it this far and it seems as if though I can't get my head
around getting the top half to work..
You've got the right idea. This program only prints the "bottom"
triangle. Consider this strategy: Put this program aside for now, and
start writing a new program; one which only prints the "top" triangle.
Then, take both programs and try to combine them together, to see if
you can produce the whole figure. You'll probably have 2 sets of nested
loops, e.g.
for (something) {
for (something) {
do something;
}
}
for (something) {
for (something) {
do something;
}
}
- Oliver