Search code examples
javanested-for-loop

trying to print a square of X's and Y's using nested for loops


Input:

3
7
4

Output:

XXXY
XXYY
XYYY

XXXXXXXY
XXXXXXYY
XXXXXYYY
XXXXYYYY
XXXYYYYY
XXYYYYYY
XYYYYYYY

XXXXY
XXXYY
XXYYY
XYYYY

I have an idea that involves 2 for loops nested in another for loop that would look something like:

  String ret = "";
  for (int row = 0; row < size; row++) //size is the input
  {
    for (int col = 0; col < size; col++)
    {
      ret += "X";
    }
    for (int col = 0; col < size; col++)
    {
      ret += "Y";
    }
    ret += "\n";
  }
  return ret;

This code would output:

XXXYYY
XXXYYY
XXXYYY

XXXXXXXYYYYYYY
XXXXXXXYYYYYYY
XXXXXXXYYYYYYY
XXXXXXXYYYYYYY
XXXXXXXYYYYYYY
XXXXXXXYYYYYYY
XXXXXXXYYYYYYY

XXXXYYYY
XXXXYYYY
XXXXYYYY
XXXXYYYY

I can't really figure out how to get this working, any help is much appreciated.


Solution

  • You need to change the < from the third for loop to <= and change the size argument to the iterative row (or size-row for the inverse)

    String ret = "";
    for (int row = 0; row < size; row++){
      for (let col = 0; col < size-row; col++){
        ret += "X";
      }
      for (int col = 0; col <= row; col++){
        ret += "Y";
      }
      ret += "\n";
    }
    return ret;