C#, 203 202 196 193 178 bytes
n=>{var r=new int[n,n];for(int o=n-2+n%2>>1,i=r[o,o]=1,c=2,w=o,h=o,b=1-2*(i%2),j;n>i++;){r[h,w+=b]=c++;for(j=0;j<i-1;++j)r[h+=b,w]=c++;for(j=0;j<i-1;++j)r[h,w-=b]=c++;}return r;}
Saved a byte thanks to @StefanDelport.
Saved 22 bytes thanks to @FelipeNardiBatista.
This works by the following observation of how the squares are built up:

As you can see each bit is added on to the previous square. For even numbers we go right of where we were, down till were one lower than where the square was and then left to the end. Odd numbers are essentially the opposite, we go left one, up till were one above the current height and then right to the end.
Full/Formatted version:
using System;
using System.Linq;
class P
{
static void Main()
{
Func<int, int[,]> f = n =>
{
var r = new int[n, n];
for (int o = n - 2 + n % 2 >> 1, i = r[o, o] = 1, c = 2, w = o, h = o, b = 1 - 2 * (i % 2), j; n > i++;)
{
r[h, w += b] = c++;
for (j = 0; j < i - 1; ++j)
r[h += b, w] = c++;
for (j = 0; j < i - 1; ++j)
r[h, w -= b] = c++;
}
return r;
};
Console.WriteLine(String.Join("\n", f(3).ToJagged().Select(line => String.Join(" ", line.Select(l => (l + "").PadLeft(2))))) + "\n");
Console.WriteLine(String.Join("\n", f(4).ToJagged().Select(line => String.Join(" ", line.Select(l => (l + "").PadLeft(2))))) + "\n");
Console.WriteLine(String.Join("\n", f(5).ToJagged().Select(line => String.Join(" ", line.Select(l => (l + "").PadLeft(2))))) + "\n");
Console.ReadLine();
}
}
public static class ArrayExtensions
{
public static T[][] ToJagged<T>(this T[,] value)
{
T[][] result = new T[value.GetLength(0)][];
for (int i = 0; i < value.GetLength(0); ++i)
result[i] = new T[value.GetLength(1)];
for (int i = 0; i < value.GetLength(0); ++i)
for (int j = 0; j < value.GetLength(1); ++j)
result[i][j] = value[i, j];
return result;
}
}
4Example:
4
? Or any even number. – TheLethalCoder – 8 years agoMay we output an array of arrays of ints? – TheLethalCoder – 8 years ago
1May we assume the input is odd? – Mr. Xcoder – 8 years ago
1Related – Emigna – 8 years ago
Related Project Euler problem – Okx – 8 years ago
@Okx I was inspired by that. – Julius – 8 years ago
@TheLethalCoder I added an example for n = 4. – Julius – 8 years ago
2Possible dupe? – Shaggy – 8 years ago
Can the lines be outputted as an array or a sequence of cells? (asking for brainfuck) – Uriel – 8 years ago
@Uriel No, please print the output in a grid. – Julius – 8 years ago
1
See also http://www.perlmonks.com/?node_id=487200 with many solutions and links in replies.
– b_jonas – 8 years agoRelated: Determine the position of a non-negative number in the infinite spiral. – user202729 – 7 years ago