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

Time:12-06

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.

CodePudding user response:

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;
  • Related