Reputation: 197
I have written the code for printing slash using 2 for loops. How can I print the same using only one for loop?
public static void main(String[] args)
{
int i,j;char[][] ch=new char[100][100];
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
if(i==j)
ch[i][j]='*';
else
ch[i][j]=' ';
System.out.print(ch[i][j]);
}
System.out.println(' ');
}
Upvotes: 2
Views: 658
Reputation: 466
Still slower:
For(int i = 0; i < width*height; i++) {
Int x = i%height
Int y = (i-x)/height
// Code using ch[x][y]
}
Edited via phone :)
Upvotes: 2
Reputation: 88378
Here is one way:
import java.util.Arrays;
public class App {
public static void main(String[] args) {
char[] line = new char[100];
for (int i = 0; i < 4; i++) {
Arrays.fill(line, ' ');
line[i] = '*';
System.out.println(line);
}
}
}
The idea is to use array-based operations (in this case, fill
) to avoid one of the explicit loops.
Upvotes: 2