Why did some dinosaurs have horns?

Horns and frills could scare predators, lock heads in shoving matches, or impress mates.