The problem is to create concentric and nested squares,starting with the largest square’s side given as N.Its just like drawing one square inside another ON PAPER,until no more squares are possible to be drawn, by decrementing the length of the side by 4 after each square(2 from startPos of side and 2 from endPos); And N is the size of the square to start with.
You have to draw the sides by using multiplication symbol(‘*’).
The proportion(looks more like rectangles than squares) of the above image might not be exact, but it would give u idea about what needs to be done ..
The below code is what I have tried…
public static void main(String[] args)
{
int N=9;
int iLo=0;
int iHi=N-1;
int jLo=0;
int jHi=N-1;
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
if(i==0 || (i==N-1) || (j==0) || (j==N-1))
System.out.print('*');
else
{
if(i<=N/2)
{
if((i%2==0) && (i>=iLo) && (i<=iHi) && (j>=jLo) && (j<=jHi))
System.out.print('*');
else
if(i==iLo || i==iHi )
System.out.print('*');
else
System.out.print(' ');
}
else
{
if((i%2==0) && (i>=iLo) && (i<=iHi) && (j>=jLo) && (j<=jHi))
System.out.print('*');
else
System.out.print(' ');
}
}
}
System.out.print(" i-->"+i+" iLo-->"+iLo+" iHi-->"+iHi+" jLo-->"+jLo+" jHi-->"+jHi);
if(i%2>0)
{
if(i<=N/2)
{
jLo=jLo+2;
jHi=jHi-2;
iLo=iLo+1;
iHi=iHi-1;
}
else
{
jLo=jLo-2;
jHi=jHi+2;
iLo=iLo-1;
iHi=iHi+1;
}
}
else
{
}
System.out.println();
}
}
The following code offers the simplest recursive solution possible—
public class SquaresInSquare {
}