To be a bit more specific: The formula 2n^2 is based on the assumption that the shells are hydrogen like. There are deviations from this rule.
The factor 2 is due to the fact that each orbital can carry at most two electrons, one with spin up, the other with spin down.
So we have to explain why there are n^2 orbitals in each shell.
It is a peculiarity of the hydrogen atom that all orbitals having the same number of node surfaces have the same energy. There are radial nodes and spherical nodes. All orbitals in a given shell have n-1 nodes. The number of spherical nodes fixes whether we speak of an s, p, d, or f orbital. The number of spherical nodes is equal to the quantum number l with l=0 corresponding to s, l=1 to p etc. There are 2l+1 orbitals with the same value of l. So if e.g. n=4 the orbitals have 3 nodes. There are the following possibilities
# radial nodes #spherical nodes=l name multiplicity=2l+1
0 3 f 7
1 2 d 5
2 1 p 3
3 0 s 1
You can check that the sum of the multiplicities is 16=n^2.
In general ##\sum_{l=0}^{n-1}(2l+1)=n^2##
as Kolmogorow, the father of modern statistics, realized as a 5 year old boy.