"In a co-ordinate system i have to place some n elements in a square format as shown in fig. with a distance r. "
Distance between two consecutive points horizontally and vertically r or distance to nearest neighbor r? (I'm going to assume "horizontally and vertically". If you meant straight line distance r, take my r to be your r divided by sqrt(2).)
You probably realized, since you have two pictures, that the problems breaks down into two cases: number of elements odd or even.
In either case, let m= sqrt(n) (by the conditions of the problem, m is also an integer.)
If n, number of elements is odd, m is also odd: let k= (m-1)/2 (so that m= 2k+1)Then there exist a point at the origin (0,0). Every point has coordinates (ir, jr) where i and j run from -k to k by integers (including 0, of course). An algorithm to plot them might be
For (integer)i= -k to k, step 1
{
For (integer j= -k to k, step 1
{
plot(i*r,j*r);
}
}
For example, if n= 9, then m= 3 and k= 1. The 9 points would have coordinates
(-r,-r), (0,-r),(r,-r), (0,-r), (0,0), (0,r), (r,-r), (r,0), and (r,r).
if n is even, then m is also even and m= 2k for some integer k. Now all points are of the form ((i+1/2)r, (j+1/2)r) for i= 1 to k and i= -1 to -k (skipping over 0). An algorithm to plot them (but not in the same order as above) might be:
For (integer)i= 1 to k, step 1
{
For (integer)j= 1 to k, step 1
{
plot((i+1/2)r,(j+1/2)r)
plot((-i-1/2)r,(-j-1/2)r)
}
}