The earth was formed sometime about 4.6 billion years ago. The earth was mostly in a volatile state during its primordial stage. Due to a gradual increase in density the temperature inside has increased. As a result, the material inside started getting separated depending on their densities. This allowed heavier materials (like iron) to sink towards the centre of the earth and the lighter ones to move towards the surface. Starting from the surface to the central parts, we have layers like the crust, mantle, outer core and inner core. From the crust to the core, the density of the material increases.