PRINTING DIAMOND SHAPE WITH LOOPS!

P

Paul Lutus

Gordon said:
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)

Yes, true, point taken, but I can think of several ways to force an action
instead of an assignment using the ternary operator. Just for the sake of
argument, you understand.
If you want statements ("do this"), an if/else construction is more
appropriate.

Unless you are enamored of obscure programming styles, a la Perl. Or, like
me, you are sometimes not vigilant about the placement of verbs.
 
J

Jay Dean

Okay, Paul, et al.,
I tried the implementation of the shape again. This time I came soo
close. My main problem is where I have indicated with (---) in the
second else if condition. If you remove && j< (----) from it and test
it, you will see exactly what I am talking about. If I
replace(----)with m, where m is an int m=n; and then put m--; after
j++; at the end of the outer loop, it does not work. I would
appreciate your help with this.
Also, I have a few questions below the code I need help with:

int n=7,marker=(n/2)+1,i=1,j=1;

while(i<=n)
{
while(j<=n)
{
if((i<marker)&&((marker-i)<j && j <(marker+i)))
{System.out.print("*");}

else if((i==marker))
{System.out.print("*");}

else if((i>marker)&&((i-marker)<j && j < (----)))
{System.out.print("*");}

else
{System.out.print(" ");}
j++;
}
System.out.println("");
i++;
j=1;
}

- In Java, if say I print out 7 rows of stars and at the end I want
to go back to the very beginning of the first line, or any other line
apart from the last one,how do I do that?

- My guess is that (boolean)?(true):(false); is some sort of a
condensed if-else clause. If so, is there a limit on the lines of code
that one can put in place of the (true) and the (false)?

- If say, 5 rows of dots are printed using System.out.print(ln), to
the screen, is it possible to create a second code that traverses the
dots and removes or erases some of them as I wish?

- Does the Java API provide any info on ALL Java operators and
symbols?

I would appreciate your help.Thanks..

Jay Dean
 
P

Peter Davis

- In Java, if say I print out 7 rows of stars and at the end I want
to go back to the very beginning of the first line, or any other line
apart from the last one,how do I do that?

You can't. Not with System.out.print(), anyway. System.out is a
"stream", meaning you can only write to it in order -- there is no
rewinding or jumping around in the stream.

Fortunately, there are countless ways to write this algorithm that
don't require jumping around in the output stream.

When I want to write an algorithm (in general), I try to think like the
computer. I know what restrictions I have to work within, and what
tools I have available to solve the problem. Then, I walk through the
algorithm, step by step, in my head, before I write any code.

So, you know (now) that whatever your solution is in the end, it has to
print the stars, spaces, and lines in a stream. If you were the
computer, try to imagine how you'd go about drawing a diamond. Imagine
drawing each star, space, and newline-character ('\n') one by one, and
think about the variables you'll need to keep track of your progress.
- My guess is that (boolean)?(true):(false); is some sort of a
condensed if-else clause. If so, is there a limit on the lines of code
that one can put in place of the (true) and the (false)?

Yes, the limit is that you can put *less than one* lines of code :).

The boolean?true:false construct is an expression, not a statement. So
you can't do something like this, all on its own:

(-1 < 3) ? System.out.println("true") : System.out.println("false");

(Try it, it won't compile).

But you can do this:

System.out.println((-1 < 3) ? "true" : "false");

The "true" and "false" parts have to be values, or expressions that
evaluate to values, but can't be statements on your own. That's why we
have if(...) {...} else {...}.
- If say, 5 rows of dots are printed using System.out.print(ln), to
the screen, is it possible to create a second code that traverses the
dots and removes or erases some of them as I wish?

Not using the System.out stream. If you were to construct the diamond
as a String or StringBuffer in memory all at once before printing it,
it would be possible. But since it's possible without resorting to
such hackery, don't :).
- Does the Java API provide any info on ALL Java operators and
symbols?

I assume you're talking about the API reference on Sun's website -- the
answer is no, that reference only talks about classes and methods.

Here's a tutorial on all the Java operators:

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/operators.html

And for the ultimate reference, try reading:

http://java.sun.com/docs/books/jls/second_edition/html/jTOC.doc.html
 
J

Joona I Palaste

Yes, the limit is that you can put *less than one* lines of code :).
The boolean?true:false construct is an expression, not a statement. So
you can't do something like this, all on its own:
(-1 < 3) ? System.out.println("true") : System.out.println("false");
(Try it, it won't compile).
But you can do this:
System.out.println((-1 < 3) ? "true" : "false");
The "true" and "false" parts have to be values, or expressions that
evaluate to values, but can't be statements on your own. That's why we
have if(...) {...} else {...}.

However, you can do this:

private String doIt(String value) {
System.out.println(value);
return null;
}

String dummy = (-1 < 3) ? doIt("true") : doIt("false");
 
J

Joona I Palaste

However, you can do this:
private String doIt(String value) {
System.out.println(value);
return null;
}
String dummy = (-1 < 3) ? doIt("true") : doIt("false");

Just thought I'd add something to help the OP.
When you have an expression of the form:
(condition) ? (true_part) : (false_part)
Then you are guaranteed that (condition) is always evaluated first, and
then exactly *ONE* of (true_part) and (false_part) is evaluated.
Normally this wouldn't matter, but in Java (like in C) expressions can
have side effects. They can call methods (such as I wrote above) or
modify variables.
 
J

Joona I Palaste

Just thought I'd add something to help the OP.
When you have an expression of the form:
(condition) ? (true_part) : (false_part)
Then you are guaranteed that (condition) is always evaluated first, and
then exactly *ONE* of (true_part) and (false_part) is evaluated.
Normally this wouldn't matter, but in Java (like in C) expressions can
have side effects. They can call methods (such as I wrote above) or
modify variables.

Oh, and furthermore...
The types of (true_part) and (false_part) must be assignment-compatible.
This means that at least one of the expressions must be assignable into
a variable of the type of the other.
This means you can't do this:
Object obj = (-1 < 3) ? new Integer(1) : new ArrayList();
because you can't assign an Integer to an ArrayList variable or the
other way around. However you can do this:
Object obj = (-1 < 3) ? (Object)new Integer(1) :
(Object)new ArrayList();
because you can assign both Integers and ArrayLists to Object variables.
One of the very rare cases when upcasting is ever needed in Java.
 
J

Jay Dean

Thank you very much, Peter & Joona, for your your very insightful
inputs into my questions. I also appreciate the links you provided.You
have no idea how much you have helped me out.

Thanks again.
Jay Dean
 
J

Joona I Palaste

Jay Dean said:
Thank you very much, Peter & Joona, for your your very insightful
inputs into my questions. I also appreciate the links you provided.You
have no idea how much you have helped me out.
Thanks again.
Jay Dean

Hey, thanks for the compliments. I'm honoured if I can help someone in
studying Java programming.
 
J

jyothi.m1089

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( "" );
}
}
}

can you please explain the logic of this program....
 
M

Mike Amling

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
 
P

pchristor

run your program in an IDE with the trace option. You can see it

working.

--

Roedy Green Canadian Mind Products http://mindprod.com

Unlike many machines, computers require no water once they are

manufactured.

Here is another option:

public static void main(String[] args) {

int x=9;
int m=x/2;
StringBuilder str1= new StringBuilder(x);
for(int i=0; i<m; i++){str1.append(" ");}
str1.append("*");
System.out.println(str1.toString());
for(int j=1; j<x; j++){
if(j<=m){ str1.deleteCharAt(m-j);
str1.append("**");
}else{
str1.delete(m,m+2 ); str1.insert(0, " ");
}
System.out.println(str1.toString());
}
}
 
L

Lew

Here is another option:

public static void main(String[] args) {

int x=9;
int m=x/2;
StringBuilder str1= new StringBuilder(x);
for(int i=0; i<m; i++){str1.append(" ");}
str1.append("*");
System.out.println(str1.toString());
for(int j=1; j<x; j++){
if(j<=m){ str1.deleteCharAt(m-j);
str1.append("**");
}else{
str1.delete(m,m+2 ); str1.insert(0, " ");
}
System.out.println(str1.toString());
}
}

Seriously, dude?

Start by following the coding conventions, please.

Then we can help with the logic, should we be so bold.
 
A

Arne Vajhøj

Here is another option:

public static void main(String[] args) {

int x=9;
int m=x/2;
StringBuilder str1= new StringBuilder(x);
for(int i=0; i<m; i++){str1.append(" ");}
str1.append("*");
System.out.println(str1.toString());
for(int j=1; j<x; j++){
if(j<=m){ str1.deleteCharAt(m-j);
str1.append("**");
}else{
str1.delete(m,m+2 ); str1.insert(0, " ");
}
System.out.println(str1.toString());
}
}

Seriously, dude?

Start by following the coding conventions, please.

Then we can help with the logic, should we be so bold.

I am afraid that it was an answer not a question.

:)

Arne
 
P

pchristor

Here is another option:
public static void main(String[] args) {
int x=9;
int m=x/2;
StringBuilder str1= new StringBuilder(x);
for(int i=0; i<m; i++){str1.append(" ");}


for(int j=1; j<x; j++){



str1.delete(m,m+2 ); str1.insert(0, " ");



}



Seriously, dude?



Start by following the coding conventions, please.



Then we can help with the logic, should we be so bold.

What coding conventions are not being followed?
 
P

pchristor

Indentation, new lines and the usage of spaces are all

non standard.



Arne

I'm afraid the spaces are necessary.I would like to see your standard code,which contains no spaces, please post a short example.

I don't see how this answers the question about coding conventions. Is "non-standard" == "not following coding conventions" ??
 
J

Joerg Meier

I'm afraid the spaces are necessary.I would like to see your standard code, which contains no spaces, please post a short example.

Nobody said all spaces are unneccessary. Arne said that YOUR USAGE of them
is NON STANDARD.
I don't see how this answers the question about coding conventions. Is "non-standard" == "not following coding conventions" ??

It is. The coding conventions set a standard of how to do these things. You
are doing them differently, which makes your code unpleasant to read for
those of us who do and are used to look at proper formatting.

Liebe Gruesse,
Joerg
 

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

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,050
Latest member
AngelS122

Latest Threads

Top