How to evenly distribute squares in a rectangular area?

i need to figure out how can i add given number of squares in a rectangle i want to create this. http://i.stack.imgur.com/MHoda.jpg

The whole scenario is to create a function that take a number and then create a layout of it, for a quick reference i did this with predefined values for rows, columns, x&y scale etc. The size of the rectangle is fixed and it will always be something predefined, everything else need to be calculated with these values. Can anybody help me please??

The first step is to figure out how many rows $R$ and columns $C$ you want. If you want N squares, you need $R*C\ge N$. If you are given the dimensions of the rectangle, say w is the ratio of the width $W$ to the height $H$(presumed $\ge 1$). Then you probably want $C/R$ to be about this, so $R^2w \ge N$ Now you can round up to get $R$ and divide and round up to get $C$.
To get the coordinates of each square of side $s$, there is some space $t$ between the squares. So $Cs+(C-1)t\le W$ and $Rs+(R-1)t\le H$ and you lay them out starting at (0,0) if that is top left in increments of $s+t$