Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading