Anantha Raman Anantha Raman - 5 months ago 28
Java Question

Pattern printing using single loop

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(' ');
}

Answer

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.