Writing a nested loop with a single for loop (generic) - java
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 o开发者_开发技巧f 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?
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!)
You can use multiple conditions inside for loop
int w = 0;
for(int i = 0; i < height * width; i++)
{
System.out.print("*");
if( ++w >= width ) {
w = 0;
System.out.println();
}
}
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.
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 ++;
}
}
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
精彩评论