PRINTING DIAMOND SHAPE WITH LOOPS!

J

Jay Dean

I need simple nested loops (either for, or while) code for a method to
print a diamond shaped stars for n stars, where n is odd.
Example. n=9 would produce

*
***
*****
*******
*********
*******
*****
****
*
I have STRUGGLED with this for over three days in a row and my head
aches!
I tried with nested loops, and conditions but the results were not
encouraging.
I am a novice in Java and need help with simple nested loops to
construct this. Thanks in advance for your help !!

Jay Dean
 
C

Cid

I need simple nested loops (either for, or while) code for a method to
print a diamond shaped stars for n stars, where n is odd. ....
I have STRUGGLED with this for over three days in a row and my head
aches!
I tried with nested loops, and conditions but the results were not
encouraging.
I am a novice in Java and need help with simple nested loops to
construct this. Thanks in advance for your help !!


1. comp.lang.java.help is a more appropriate group for intro questions

2. when you repost there, include your current sample code and
explanation of exactly what part of the logic is throwing you. That
way people will see that you're actually working on it and not asking
them to do your homework for you.
 
P

Paul Lutus

Jay said:
I need simple nested loops (either for, or while) code for a method to
print a diamond shaped stars for n stars, where n is odd.
Example. n=9 would produce

*
***
*****
*******
*********
*******
*****
****
*
I have STRUGGLED with this for over three days in a row and my head
aches!

And to think you could have stopped and read your textbook for a while. That
would have been more productive.
I tried with nested loops, and conditions but the results were not
encouraging.

I guess so, since you couldn't bring yourself to post the result.
I am a novice in Java and need help with simple nested loops to
construct this.

Okay, here's my advice. Post your code if you expect help.
 
H

Hal Rosser

Jay Dean said:
I need simple nested loops (either for, or while) code for a method to
print a diamond shaped stars for n stars, where n is odd.
Example. n=9 would produce

*
***
*****
*******
*********
*******
*****
****
*
I have STRUGGLED with this for over three days in a row and my head
aches!
I tried with nested loops, and conditions but the results were not
encouraging.
I am a novice in Java and need help with simple nested loops to
construct this. Thanks in advance for your help !!

Jay Dean

Jay,
Being a beginner at programming, it may be a good idea to plan it out first.
you typed out what you want your program to do, so you should make note of
what you did.
For instance, note that the number of spaces before the "*" starts at a
maximum value and decreases by one after each print.
Also note the number of "*"s increase from one to a maximum value - then
decreases by one to one.
You're on the right track of using nested loops - you need to increment one
value and decrement another value.
Its a good exercise in planning your app.
Use flowcharts to plan if it makes things clearer for you.
Plan first - then write the code.
Hope this helps
Hal
 
L

Liz

Hal Rosser said:
Jay,
Being a beginner at programming, it may be a good idea to plan it out first.
you typed out what you want your program to do, so you should make note of
what you did.
For instance, note that the number of spaces before the "*" starts at a
maximum value and decreases by one after each print.
Also note the number of "*"s increase from one to a maximum value - then
decreases by one to one.
You're on the right track of using nested loops - you need to increment one
value and decrement another value.
Its a good exercise in planning your app.
Use flowcharts to plan if it makes things clearer for you.
Plan first - then write the code.
Hope this helps
Hal
---------------------

class Test7
{
public static final void main( String[] args )
{
int n = Integer.parseInt( args[ 0 ] );
for ( int i = 1; i <= n; i += 2 )
{
for ( int k = 0; k < ( n - i ); k += 2 )
System.out.print( " " );
for ( int j = 0; j < ( ( i * 2 ) - 1 ); j += 2 )
System.out.print( "*" );
System.out.println( "" );
}
for ( int i = 1; i <= n; i += 2 )
{
for ( int k = 1; k < i; k += 2 )
System.out.print( " " );
for ( int j = 0; j <= ( n - i ); j++ )
System.out.print( "*" );
System.out.println( "" );
}
}
}
 
L

Liz

Liz said:
---------------------
small mistake - new version
-----------------------class Test7
{
public static final void main( String[] args )
{
int n = Integer.parseInt( args[ 0 ] );
for ( int i = 1; i <= n; i += 2 )
{
for ( int k = 0; k < ( n - i ); k += 2 )
System.out.print( " " );
for ( int j = 0; j < ( ( i * 2 ) - 1 ); j += 2 )
System.out.print( "*" );
System.out.println( "" );
}
for ( int i = 1; i <= n; i += 2 )
{
for ( int k = 0; k < i; k += 2 )
System.out.print( " " );
for ( int j = 2; j <= ( n - i ); j++ )
System.out.print( "*" );
System.out.println( "" );
}
}
}
 
A

Adam

Ok, this is your lucky day, I had to wake up so
wrote what's below.
Maybe you'll learn by looking at an example...

public class Stars
{
public static void main(String[] args)
{
System.out.println("Parameter needed (an odd number)");
System.out.println("Example: java Stars 7");
System.out.println();
int longestRow = Integer.parseInt(args[0]);

for(int row=1 ; row<=longestRow ; ++row)
{
int i = (2*row) - 1;
if(i>longestRow) i = 2*(longestRow-row+1) - 1;
for(int j=0 ; j<(longestRow-i)/2 ; ++j) System.out.print(" ");
for(int j=0 ; j<i ; ++j) System.out.print("*");
for(int j=0 ; j<(longestRow-i)/2 ; ++j) System.out.print(" ");
System.out.println();
}
}
}
 
J

Jay Dean

Cid -
I appreciate your redirecting me to the .lang group. As I
indicated, I am a novice and did not know where exactly to post
questions.
However, it is very *ridiculous* for a lot of helpers to *assume*
that most questions are HOMEWORKS. You certainly don't know me, and
can't tell me for sure that I am in school.Even if it were a homework,
and you "help" a student it is the student who is "hurting"
him/herself. If you can help somebody, help him/her. You have nothing
to lose by doing that. My assumption was that newsgroups were a
platform for information sharing.
Please if you do not want to help somebody with a question,leave
the qusetion alone, because someone else might. This forum is
certainly NOT your private venture.
This was a question from a book I was given on my job to study
java. I AM NOT A STUDENT! Thanks for your help!

Jay Dean.
 
J

Joona I Palaste

Cid -
I appreciate your redirecting me to the .lang group. As I
indicated, I am a novice and did not know where exactly to post
questions.
However, it is very *ridiculous* for a lot of helpers to *assume*
that most questions are HOMEWORKS. You certainly don't know me, and
can't tell me for sure that I am in school.Even if it were a homework,
and you "help" a student it is the student who is "hurting"
him/herself. If you can help somebody, help him/her. You have nothing
to lose by doing that. My assumption was that newsgroups were a
platform for information sharing.
Please if you do not want to help somebody with a question,leave
the qusetion alone, because someone else might. This forum is
certainly NOT your private venture.
This was a question from a book I was given on my job to study
java. I AM NOT A STUDENT! Thanks for your help!

Don't top-post. Fixed.
I appreciate the fact that you are not a student doing homework, but
instead trying to learn Java at your job. Thus Cid was wrong to
immediately assume it was homework.
However, asking people to write programs for you will not help you
learn Java, regardless of whether you are studying it at school or at
your job. Thus Cid was right in saying that people will not write
your programs for you.
I see you have already got at least one reply giving details on the
sort of algorithm you should implement. You would do well to read it.
Liz, OTOH, seems to have given you a complete program without even
explaining its code. If you type this in ready-made, it is possible
that all it teaches you is how to type in ready-made code.

--
/-- Joona Palaste ([email protected]) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"'It can be easily shown that' means 'I saw a proof of this once (which I didn't
understand) which I can no longer remember'."
- A maths teacher
 
P

Paul Lutus

Jay said:
Cid -
I appreciate your redirecting me to the .lang group. As I
indicated, I am a novice and did not know where exactly to post
questions.
However, it is very *ridiculous* for a lot of helpers to *assume*
that most questions are HOMEWORKS.

WHAT? You have a JOB in which someone wants you to create the classic
student diamond algorithm, but for some reason you CAN'T think of how to do
it? Yeah, right.

No assumptions were made. Not one. You are a student who wants people to
tell you how to solve problems you should sort out for yourself.

Serious students post code. Dropouts post excuses.
You certainly don't know me, and
can't tell me for sure that I am in school.

But you have told us volumes about yourself. Top of the list, for some
reason you want to lie about being a programming student.
Even if it were a homework,
and you "help" a student it is the student who is "hurting"
him/herself. If you can help somebody, help him/her.

To hurt themselves? What weird values you have.
You have nothing
to lose by doing that.
False.

My assumption was that newsgroups were a
platform for information sharing.

Your assumption that newsgroups are a way to avoid thinking is mistaken.
Please if you do not want to help somebody with a question,leave
the qusetion alone, because someone else might. This forum is
certainly NOT your private venture.

It is most certainly not your automatic answer machine.
This was a question from a book I was given on my job to study
java. I AM NOT A STUDENT!

You just contradicted yourself:

1. "This was a question from a book I was given on my job to study java."

Book, study, Java: A student of Java.

2. "I AM NOT A STUDENT!"

Not a student of Java.

Perfect.
 
P

Paul Lutus

Jay said:
I need simple nested loops (either for, or while) code for a method to
print a diamond shaped stars for n stars, where n is odd.
Example. n=9 would produce

*
***
*****
*******
*********
*******
*****
****
*
I have STRUGGLED with this for over three days in a row and my head
aches!

Well, since you aren't really interested in learning this:

void drawDiamond(int n)
{
int q = n/2;
for(int a = -q;a <= q;a++) {
int b = (a < 0)?-a:a;
int c = q-b;
for(int d = 0;d <= q+c;d++) {
System.out.print((d < b)?" ":"*");
}
System.out.println();
}
}

n = 9:

*
***
*****
*******
*********
*******
*****
***
*

We would gladly teach you how to fish, but you clearly want to be handed the
fish. So be it.
 
C

Chris Uppal

Jay said:
However, it is very *ridiculous* for a lot of helpers to *assume*
that most questions are HOMEWORKS.

I would say that it's very sensible assumption. Not only is it the assumption
I
made myself, but I would question the sense/experience of anyone who /didn't/
make it.

You certainly don't know me, and
can't tell me for sure that I am in school.

Exactly, that's why we have to assume what's most probable given incomplete
information.

There have been before, and there will be again, cases where people post
requests for help with trivially simple exercises who are not looking for help
with schoolwork, but such cases are in the small minority.

BTW, please don't take offence at the phrase "trivially simple" -- it /is/
trivial for any working (or otherwise experienced) programmer, but everyone has
to start somewhere.

Even if it were a homework,
and you "help" a student it is the student who is "hurting"
him/herself. If you can help somebody, help him/her. You have nothing
to lose by doing that.

You may find this hard to believe, but /ALL/ of the responses you got were
genuine attempts to help you. It may not have been the help you /thought/ you
needed, but they were all offering constructive advice in their own ways.

BTW, now that you've been given a complete solution (which I haven't bothered
to read) I advise you to see if you've learned anything from it. I suggest you
close down your newsreader (so you are not tempted to "cheat") and then see if
you can solve the problem on your own. You will almost certainly find it
easier to start with couple of simpler problems, first to print a simple
triangle:

*
**
***
****

and then to print a backwards triangle:

*
**
***
****

-- chris
 
J

John

Paul said:
Jay Dean wrote:




Well, since you aren't really interested in learning this:

void drawDiamond(int n)
{
int q = n/2;
for(int a = -q;a <= q;a++) {
int b = (a < 0)?-a:a;
int c = q-b;
for(int d = 0;d <= q+c;d++) {
System.out.print((d < b)?" ":"*");
}
System.out.println();
}
}

n = 9:

*
***
*****
*******
*********
*******
*****
***
*

We would gladly teach you how to fish, but you clearly want to be handed the
fish. So be it.

Nice solution. The OP might be able to explain its workings to the
lecturer though. Here's a more confusing version. I just wish I could
justify some bitwise operations here.

static void drawDiamond(int n) {
for(int i = -n/2;i <= n/2; i++) {
for(int j=0;j <= n-1-((i < 0)?-i:i);j++) {
System.out.print((j < ((i < 0)?-i:i))?" ":"*");
}
System.out.println();
}
}
 
P

Paul Lutus

John said:
Nice solution. The OP might be able to explain its workings to the
lecturer though. Here's a more confusing version. I just wish I could
justify some bitwise operations here.

static void drawDiamond(int n) {
for(int i = -n/2;i <= n/2; i++) {
for(int j=0;j <= n-1-((i < 0)?-i:i);j++) {
System.out.print((j < ((i < 0)?-i:i))?" ":"*");
}
System.out.println();
}
}

Yes, I agree. Yours is an example of a perfectly good working solution that
no sane student would dare turn in, because he might have to try to explain
it. :)
 
A

arne thormodsen

static void drawDiamond(int n) {
Yes, I agree. Yours is an example of a perfectly good working solution that
no sane student would dare turn in, because he might have to try to explain
it. :)

I sense an "obsfuscated code" contest here... ;-)

You might try replacing the "/2" operations with some bit-shifting
logic to start with.

Also, rather than use the ternary operator to decide on the character
to print, why not calculate it's UNICODE value from some formula based
on the index values?

If I wasn't already occupied this could be fun!

--arne
 
J

Jay Dean

Paul,John,Adam,Liz, at al.,.
Thank you all for your individual help and input into trying to
helping me. Sorry, all I needed was one sentence:"Post your code that
is not working". Instead, I was subjected to all sorts of unfair
stereotypes. But, I perfectly understand where you are coming from,
and I appreciate that.
Anyway, I tested John and Paul's codes in a main method and
they worked perfectly,even thogh Paul intentionally meant to confuse
me.
However, I have two main issues...
(1)I STILL want HELP to implement the method with one of my OWN
UNFINISHED codes below and
(2) I would like you to help me understand your code with clear
commenting if possible..., especially, does a "-" sign in front of an
int variable imply ("opposite direction")? Also, what do the symbols
?,:,etc mean in Java? I have a general understanding of the logical
operators, or, and, xor etc but not the ?,: and the rest

(1). Here's one of my many attempts that I have struggled with for
days:

int n=9,allrows=n, allcols=n, i=1, j=1,totalstars=1,starlimit=1;
String s ="*";

while(i < allrows+1 )//loop for making rows
{
while(j < allcols+1)// loop for making columns.
{
while((j >=(((allrows+1)/2)-i)) && (totalstars < starlimit+1))//
create top stars
{
if(i=((n+1)/2)+1) break;// if it gets to 1 more than half total
rows, stop making top stars.

System.out.print(s); // otherwise, print stars for top triangle.
j++
}
//I need help with some code here to implement the stars that form
the
// bottom triangle if everything else is correct

}
System.out.println("\n");
i++;
starlimit+=2;
totalstars+=2;
}
Please feel free to point out approaches I need to stay away from and
those i need to work harder on..etc
Also, is it advisable, if I attempted such problems with just two
whiles and if-else clauses?
Again, if I wanted to approach such a problem with first assumming
that all rows and colums are turned on (filled with 1's),i.e a
complete 2D-matrix of 1's,.. is it possible to somehow combine logical
shifts or mask( like ANDing)or some other logical operators to turn
some of the 1's off to 0's to form the shape and then print a star in
places where there are only 0's?
I guess I can think of many approaches but not knowing Java is my
real problem.

I would appreciate as much help and pointers to as many helpful
resources as possible.

Thanks,
Jay Dean.

arne thormodsen said:
Yes, I agree. Yours is an example of a perfectly good working solution that
no sane student would dare turn in, because he might have to try to explain
it. :)

I sense an "obsfuscated code" contest here... ;-)

You might try replacing the "/2" operations with some bit-shifting
logic to start with.

Also, rather than use the ternary operator to decide on the character
to print, why not calculate it's UNICODE value from some formula based
on the index values?

If I wasn't already occupied this could be fun!

--arne
 
P

Paul Lutus

Jay said:
Paul,John,Adam,Liz, at al.,.
Thank you all for your individual help and input into trying to
helping me. Sorry, all I needed was one sentence:"Post your code that
is not working". Instead, I was subjected to all sorts of unfair
stereotypes.

Neither unfair nor a stereotype. Applying a sterotype would have required us
to use our misguided imaginations instead of the content of your posts.
There was no need for that. You asked a student question, then claimed
falsely not to be a student, while explaining what kind of student you are.
No imagination required.

But we can move past that, yes?
Anyway, I tested John and Paul's codes in a main method and
they worked perfectly,even thogh Paul intentionally meant to confuse
me.

No, not at all. I meant to write a concise, efficient embodiment of the
algorithm. Its complexity to a student was a coincidental side effect.
Experienced programmers can see how it works at a glance. This makes it
space-efficient without sacrificing comprehensibility and maintainability.
However, I have two main issues...
(1)I STILL want HELP to implement the method with one of my OWN
UNFINISHED codes below

That's more like it. We are much happier helping you with your own code. You
have no idea how much more acceptable this is.
and
(2) I would like you to help me understand your code with clear
commenting if possible..., especially, does a "-" sign in front of an
int variable imply ("opposite direction")?

No, it is called a unary operator: -1 means "minus one". In the same way, -x
means "minus x".
Also, what do the symbols
?,:,etc mean in Java?

In this specific example it means:

(logical true-false test)?(do this if true):(do this if false);

Like this (not compiled or tested):

int x = -1;

System.out.println((x < 0)?"X is less than zero":"X is equal to or greater
than zero");
(1). Here's one of my many attempts that I have struggled with for
days:

Okay, with all respect I ask that you abandon this code entirely and start
with something simpler.
if(i=((n+1)/2)+1) break;

And please do not use "break" in a program of this kind! This is very bad
practice. Constructs like "break" have a place, but they are very much out
of place in a simple, deterministic algorithm like this.

1. "Divide and conquer." Start with something simple, make it work, be sure
you understand it, and move on. Do not try to solve the entire problem in
one go.

2. Experiment with loops that create a row of spaces or a row of asterisks.
Think about how they work. Do not get bogged down with ambitious blocks of
code meant to solve the main problem, but that end up not doing what you
want and that you are unwilling to abandon.

3. Think about the logical flow of the program, and how to derive all the
required values from a few variables and control structures. Build
something easy first, before moving on to the main task.

4. Avoid "break." Breaks are innately confusing and to be avoided. Including
a break in a program is in most cases an admission of defeat in sorting out
a logical control flow for the algorithm.

With all respect, fixing the code you posted would not be particularly
productive, although I want to say it sends a very positive signal of your
seriousness, and you are to be commended for doing it.
 
G

Gordon Beaton

(logical true-false test)?(do this if true):(do this if false);

A minor nit, the branches of the ternary operator are expressions, not
statements, which implies something more along the lines of:

(logical true-false test)?(this value if true):(this value if false)

If you want statements ("do this"), an if/else construction is more
appropriate.

/gordon
 
L

Larry Barowski

I sense an "obsfuscated code" contest here... ;-)

Anything worth doing is worth doing in as few lines
of code as possible.

public static void drawDiamond(int n) {
for(int i = 0; i < n * n; i++)
System.out.print((Math.abs(i%n - n/2) + Math.abs(i/n - n/2) > n/2?"
":"*") + (i%n == n-1?"\n":""));
}

or, without trailing spaces:

public static void drawDiamond(int n) {
for(int i = 0; i < n * n; i++)
System.out.print((Math.abs(i%n - n/2) + Math.abs(i/n - n/2) > n/2?(i%n
n/2)?"":" ":"*") + (i%n == n-1?"\n":""));
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,479
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top