Understanding speciation is a fundamental biological problem. It is believed that many species originated through allopatric divergence, where new species arise from geographically isolated populations of the same ancestral species. In contrast, the possibility of sympatric speciation (in which new species arise without geographical isolation) has often been dismissed, partly because of theoretical difficulties. Most previous models analysing sympatric speciation concentrated on particular aspects of the problem while neglecting others. Here we present a model that integrates a novel combination of different features and show that sympatric speciation is a likely outcome of competition for resources. We use multilocus genetics to describe sexual reproduction in an individual-based model, and we consider the evolution of assortative mating (where individuals mate preferentially with like individuals) depending either on an ecological character affecting resource use or on a selectively neutral marker trait. In both cases, evolution of assortative mating often leads to reproductive isolation between ecologically diverging subpopulations. When assortative mating depends on a marker trait, and is therefore not directly linked to resource competition, speciation occurs when genetic drift breaks the linkage equilibrium between the marker and the ecological trait. Our theory conforms well with mounting empirical evidence for the sympatric origin of many species.