SMcGwier SMcGwier - 5 months ago 14
Java Question

Diamond Using For Loop

I am attempting to have a diamond print out based on user input using for loops. I've gotten it to print out the right side of the diamond but can't get it to print out the left side. I've tried reversing my code to no avail. I'm having trouble figuring out the logic to have my code print out an entire diamond. Thanks in advance!

The expected output if num=2 is (without the lines, of course):

*
*$*
*


Here's my code so far:

//Print out a diamond shape based on user input
for (int i=num; i>0; --i){
System.out.print("*");
for (int n=i; n<num; ++n){
System.out.print("$*");
}//Ending bracket of nested for loop
System.out.println();
}//Ending bracket of for loop
//Print out a diamond shape based on user input
for (int i=0; i<num; ++i){
System.out.print("*");
for (int n=i; n<num; ++n){
System.out.print("$*");
}//Ending bracket of nested for loop
System.out.println();
}//Ending bracket of for loop

Answer

You basically only need to add another loop (one for the top half and one for the bottom half) in which you add enough spaces on each line in order to center the diamond:

for (int i=num; i>0; --i){
    //Insert spaces in order to center the diamond
    for (int n=0; n<i; ++n){
        System.out.print(" ");
    }
    System.out.print("*");
    for (int n=i; n<num; ++n){
        System.out.print("$*");
    }//Ending bracket of nested for loop
    System.out.println();
}//Ending bracket of for loop
//Print out a diamond shape based on user input
for (int i=0; i<=num; ++i){   //<= to print the last asterisk
    //Insert spaces in order to center the diamond
    for (int n=0; n<i; ++n){
        System.out.print(" ");
    }
    System.out.print("*");
    for (int n=i; n<num; ++n){
        System.out.print("$*");
    }//Ending bracket of nested for loop
    System.out.println();
}//Ending bracket of for loop

I'm not sure about the logic of the correlation between num and the shape of the diamond in your example. My code prints your desired diamond for num = 1 not num = 2. So in this code num determines the maximum width of the diamond (the number of $ signs). So num = 2 prints:

  *
 *$*
*$*$*
 *$*
  *

If you want

 *
*$*
 *

for num=1 and so on, you can simply replace every occurence of num with num-1 in the code above. Alternatively, you could also just add the line

num--;

before the code and leave the rest as it is.

Comments