Lee Morgan
Lee Morgan

Reputation: 696

Reducing a nested for loop to a single for loop

I am working on some homework for one of my classes and got a problem that I am having some trouble with. I can't quite figure out how I would do it. If somebody could point me in the right direction as to how I would go about it that would be great. Here is the question.

The nested loops

for (int i = 1; i <= height; i++)
{
    for (int j = 1; j <= width; j++) { System.out.print("*"); }
        System.out.println();
}

display a rectangle of a given width and height, such as

****
****
****

Write a single for loop that displays the same rectangle.

Upvotes: 0

Views: 6253

Answers (2)

hotzst
hotzst

Reputation: 7526

You could split up the loops in two loops that are not nested. The first look defines the String that is printed for each line:

StringBuilder sb = new StringBuilder();
for (int i = 0; i < width; i++) {
  sb.append("*");
}
String line = sb.toString();

Now you can use that line for all the rows:

for (int i = 0; i < height; i++) {
    System.out.println(line);
}

Please also not that this iterations start at index 0 and the last index is not the same as width or height, which does not make a difference here, but it is good practice, as almost everything in Java uses 0 based indices.

While this solution does not really use one single for loop like @KenBekov's, I find doing it this way is more readable.

Upvotes: 1

Ken Bekov
Ken Bekov

Reputation: 14015

for(int i=1; i<=height*width; i++) {
    System.out.print("*");
    if(i%width==0){
        System.out.println();
    }
}

Upvotes: 2

Related Questions