In nature, most bacteria live in surface-attached sedentary communities known as biofilms. Biofilms are often studied with respect to bacterial interactions. Many cells inhabiting biofilms are assumed to express 'cooperative traits', like the secretion of extracellular polysaccharides (EPS). These traits can enhance biofilm-related properties, such as stress resilience or colony expansion, while being costly to the cells that express them. In well-mixed populations cooperation is difficult to achieve, because non-cooperative individuals can reap the benefits of cooperation without having to pay the costs. The physical process of biofilm growth can, however, result in the spatial segregation of cooperative from non-cooperative individuals. This segregation can prevent non-cooperative cells from exploiting cooperative neighbors. Here we examine the interaction between spatial pattern formation and cooperation in Bacillus subtilis biofilms. We show, experimentally and by mathematical modeling, that the density of cells at the onset of biofilm growth affects pattern formation during biofilm growth. At low initial cell densities, co-cultured strains strongly segregate in space, whereas spatial segregation does not occur at high initial cell densities. As a consequence, EPS-producing cells have a competitive advantage over non-cooperative mutants when biofilms are initiated at a low density of founder cells, whereas EPS-deficient cells have an advantage at high cell densities. These results underline the importance of spatial pattern formation for competition among bacterial strains and the evolution of microbial cooperation.