tags:

views:

99

answers:

4

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?

+13  A: 

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!)

Brian Agnew
I agree. Giving HW answers is bad. Just a little hint however: you can use % operator...
miki725
A: 

You can use multiple conditions inside for loop

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

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.

M2tM