When a piece is not in the key of C Major or A Minor, it requires the use of regular accidentals. In order to avoid having to keep writing those accidentals, we can place them at the beginning of the piece using what is known as a key signature.
For instance, a piece in the key of D Major makes regular use of the notes of F-sharp and C-sharp. The key signature of D Major will then utilize those two accidentals; meaning that when this key signature is present, all F and C notes are automatically raised and become sharp notes, unless they are preceded by the symbol of the natural accidental.
Following we have a fragment from Beethoven’s famous Ode to Joy, in the key of D Major. Note how all the F and C notes are played sharp:
For more information see: