Note that there are some explanatory texts on larger screens.

plurals
  1. POprinting nested squares using for loops in Java
    text
    copied!<p><img src="https://i.stack.imgur.com/OnP5v.jpg" alt="The pattern of stars that need to be printed"> 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('*').</p> <p>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...<img src="https://i.stack.imgur.com/zdyNB.jpg" alt="This the exact pattern that needs to be printed.."></p> <pre><code>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&lt;N;i++) { for(int j=0;j&lt;N;j++) { if(i==0 || (i==N-1) || (j==0) || (j==N-1)) System.out.print('*'); else { if(i&lt;=N/2) { if((i%2==0) &amp;&amp; (i&gt;=iLo) &amp;&amp; (i&lt;=iHi) &amp;&amp; (j&gt;=jLo) &amp;&amp; (j&lt;=jHi)) System.out.print('*'); else if(i==iLo || i==iHi ) System.out.print('*'); else System.out.print(' '); } else { if((i%2==0) &amp;&amp; (i&gt;=iLo) &amp;&amp; (i&lt;=iHi) &amp;&amp; (j&gt;=jLo) &amp;&amp; (j&lt;=jHi)) System.out.print('*'); else System.out.print(' '); } } } System.out.print(" i--&gt;"+i+" iLo--&gt;"+iLo+" iHi--&gt;"+iHi+" jLo--&gt;"+jLo+" jHi--&gt;"+jHi); if(i%2&gt;0) { if(i&lt;=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(); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload