can you please explain the logic of this program....
I haven't looked at the program, but looking at the diamond I see the
first and last lines have one star, but the second and next-to-last have
three stars and four stars respectively. I assume the four-star line was
supposed to have three stars.
The number of lines to be written is n, so we might hope that an
outermost loop would look like
for (int jj=0; jj<n; ++jj) {
...
System.out.println();
}
The number of stars in each line is maximal, at n stars, when jj is
around n/2, so I'm thinking something like ss=n-abs(jj-n/2), which has
its largest value when jj=n/2 and decreases linearly as jj gets away
from n/2. If ss is not exactly right, then let's fiddle with it. For
n=9, jj=0, we want 1 star and ss is 9-5=4. For n=9, jj=4, we want 9
stars and ss is 9-0=9.
The proposed ss needs to decrease faster as jj gets away from n/2. How
about doubling the expression inside the abs()?
tt=n-abs(2*jj-n)
This decreases the number of stars by 2 for every step jj moves away
from n/2. That's good. For n=9, jj=0, tt is 9-9=0. For n=9, jj=4, tt is
9-1=8. I guess we just want to add 1 to tt to get the desired number of
stars.
uu=n-abs(2*jj-n)+1
Adding an inner loop to print the stars, we get
for (int jj=0; jj<n; ++jj) {
...
for (int kk=0; kk<n-Math.abs(2*jj-n)+1; ++kk) {
System.out.print('*');
}
System.out.println();
}
We still want some spaces before the stars, and the number of spaces is
minimal when jj=n/2 and increases as jj moves away from n/2. That suggests
vv=abs(jj-n/2)
For n=9, jj=0, vv is 4. For n=9, jj=4, vv is 0. Huh. That's exactly
correct already.
Adding an inner loop to print the spaces, we get
for (int jj=0; jj<n; ++jj) {
for (int kk=0; kk<Math.abs(jj-n/2); ++kk) {
System.out.print(' ');
}
for (int kk=0; kk<n-Math.abs(2*jj-n)+1; ++kk) {
System.out.print('*');
}
}
I think that's correct and halfway understandable.
My overdeveloped sense of microefficiency wants to avoid the possibility
that the JITC will produce code that evaluates n-Math.abs(2*jj-n)+1 more
often than necessary, so if I were actually implementing this, I would
write it as
for (int jj=0; jj<n; ++jj) {
for (int kk=Math.abs(jj-n/2); --kk>=0; ) {
System.out.print(' ');
}
for (int kk=n-Math.abs(2*jj-n)+1; --kk>=0; ) {
System.out.print('*');
}
}
Mike Amling