Search code examples
javafor-loopnested

Nested For Loop Square- Java


I am new to Java and I'm working on making a square of two triangles using a nested for loop. It is supposed to look like this:

+ + + + + 
* + + + + 
* * + + + 
* * * + + 
* * * * + 

My code looks like this so far:

for (int i = 0; i < 5; i++) {             
for (int j = 0; j < i; j++) {               
System.out.print("* ");             
}  
System.out.println();

but all it gives me is the star section of the square. I have no idea how to go from here. Can anyone help?


Solution

  • Edited to add explanation.

    The first step is to create a grid of 5 by 5. We can do that by creating two for loops, one within another. The inner for loop will print a row of * , and the outer for loop will print a new line after every row.

    The next step would be to determine when to print a + instead of a * . For your case, a simple greater than (y > x) will do the trick.

    for (int y = 0; y < 5; y++) {
        for (int x = 0; x < 5; x++) {
            System.out.print(y > x ? "* " : "+ ");
        }
        System.out.println();
    }
    

    enter image description here Demo with Desmos Graph Calculator.
    Note that the y-axis is inverted, you can use -y > x to get the correct orientation