user3050565
user3050565

Reputation: 37

Java program draw a square using for loop?

Given:

public static void printTriangle(int sideLength) 
{
    for (int i = 0; i <= sideLength; i++) {
        for (int j = 0; j < i; j++){
            System.out.print("[]");
        }
        System.out.println();
    }
}

How do you modify the code to print a square with sideLength = 3?

[][][]
[][][]
[][][]

Upvotes: 2

Views: 12429

Answers (2)

Govind Sharma
Govind Sharma

Reputation: 137

enter image description here

public class SquarPattern {

public static void main(String[] args) {

    int n = 6;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if((i==0 || i==n-1 )  || (j==0 || j==n-1)) {
              System.out.print("*");
            }else {
                  System.out.print(" ");
            }
        }
        System.out.println();
    }

}

}

Upvotes: 0

szegedi
szegedi

Reputation: 873

Like this:

public static void printSquare(int sideLength) 
{
    for (int i = 0; i < sideLength; i++) {
        for (int j = 0; j < sideLength; j++) {
            System.out.print("[]");
        }
        System.out.println();
    }
}

Upvotes: 5

Related Questions