0

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.

1
  • Apply the formula. Use for loop for generating N number of rectangle. And calculate height and width using some logics. Logica can be any of arithmetic or random. Hope you will do your homework on your own taking this suggestion. :) Commented Feb 21, 2016 at 6:50

2 Answers 2

2
for(int i=1; i<=height*width; i++) {
    System.out.print("*");
    if(i%width==0){
        System.out.println();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what I was going to post, minus half the whitespace.
1

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.

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.