Of course there is no single answer to this question. The motivation can change over time and over individuals but I will try to list a few common reasons.
For ideological reasons
People who invented free software (RMS et al.) did it originally for very ideological reasons ("all software should be free" - that is, respect four fundamental freedoms) and this was motivation enough to start the GNU project. For reference, see this 1989 NYT's article and the original GNU manifesto.
Because it's a free-time activity
Lots of people like to program so much that they do it even during their free time. When absolutely no financial benefit is to be expected from a software (either because you don't think it is worth much or because you don't want to spend time selling it), it can be seen as natural to share it as free software (it will help others and could even contribute to your own reputation).
Because it's a job
Many companies profit directly or indirectly from free and open source software (RedHat but also Google, Facebook and Microsoft) and consequently pay people to contribute to it. The most famous person to be paid for writing free software full-time is probably Linus Torvalds but there are lots of examples of people whose job is to develop proprietary software part of the time and to contribute to open source part of the time.
Github's founder and former CEO Tom Preston-Warner has a very good entry on his blog on why it pays for a company to have its employees contribute to open source software.
If you want to dive more into motivation issues, here is an academic article talking about that.
Update: And here is a 2021 academic article revisiting motivations of open source developers.