2

No one in my residence hall knows how to do this question on our CS homework. It says:

The nested loops

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

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

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

for a width of 4 and a height of 3. Write a single for loop that displays the same rectangle. Remember that 3 and 4 are only an example, and your code must be general and work for any width and height.

We have tried many things but each one ends in failure. Are we missing something obvious?

6 Answers 6

16

You should look at iterating over the total number of asterisks you need to display, and display an asterisk/newline as appropriate as you iterate through (think about how many asterisks make up a row - I don't want to give you the answer, however!)

Sign up to request clarification or add additional context in comments.

1 Comment

I agree. Giving HW answers is bad. Just a little hint however: you can use % operator...
0

You can use multiple conditions inside for loop

Comments

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

Comments

0

In a custom template language I wrote this is the solution:

{set|($height)(3) ($width)(4)}

{for|i|1 : $i <= ($height*$width) : $i++|
   *
   {if| !(($i) % $width)|
      <br/>
   }
}

I didn't want to give you the answer in Java, but it's such a simple problem that giving you advice IS solving it, so this is the best I could come up with.

Comments

0
    int width = 9 ;
    int height = 3;
    for (int row = 1, column = 1 ; row <= height && column <= width; column++) {
        System.out.print("*");
        if(column == width) {
            column = 0;
            System.out.println();
            row ++;
        }
    }

Comments

0
for (int row = 0, column = 0; (row < height && column < width); column++)
{
  System.out.print("*");
  if (column == (width - 1))
  {
    column = -1;
    row++;
    System.out.println();
    continue;
  }
}

Hope this helps.

Regards

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.