0

I need to print this: enter image description here

I need to print this square using a for loop in java.

This is what I have so far:

 public static void main(String [] args)
   {

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

    }

2 Answers 2

4

The easiest solution would be to nest two loops, first print O then use a second loop to print .. You know that each line should have a decreasing number of O (and increasing number of .s). In fact, you have 5 - i and i of each per line (where i is row number). And you can use the outer loop to determine how many of each should be drawn with those formulae. Like,

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

Which outputs (as requested)

O O O O O 
O O O O . 
O O O . . 
O O . . . 
O . . . . 

Another option would be to create a StringBuilder to represent the initial conditions, print and then mutate the StringBuilder. This uses additional storage, but eliminates the need for nested loops.

int size = 5;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; i++) {
    sb.append("O ");
}
for (int i = 0; i < size; i++) {
    System.out.println(sb);
    sb.setCharAt(sb.length() - (i * 2) - 2, '.');
}

And, you could also make that with an array of boolean(s) (e.g. a bitmask). Convert false to O and true to ., and set the last element offset by the index to true on each iteration. Like,

int size = 5;
boolean[] arr = new boolean[size];
for (int i = 0; i < size; i++) {
    for (int j = 0; j < size; j++) {
        System.out.print(arr[j] ? ". " : "O ");
    }
    System.out.println();
    arr[size - i - 1] = true;
}
Sign up to request clarification or add additional context in comments.

Comments

2

This is not a 'design pattern' problem. You just need to use the logic with loops. Here's the logic.

In a square of n x n cells, the ith row contains (n-i) ovals and i dots, where 0 <= i < n.

Refer to the other answer to see a working snippet.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.