In previous chapters, we constructed major and minor scales from modes or basic scales. Patterns of whole steps and half steps were the key to creating those scale types. As we produced the correct patterns of whole steps and half steps for each scale, accidentals were added to the mode or basic scale. Those accidentals (sharps or flats) may be grouped together at the beginning of the music immediately after the clef sign. When sharps or flats are grouped together in this manner, they are referred to as the KEY SIGNATURE.
With a KEY SIGNATURE being used, there is no need to apply accidentals to the notes within the body of the music and, so, the music is less cluttered from excessive use of accidentals. A particular sharp or flat in the KEY SIGNATURE applies to every occurrence of that note regardless of the octave (unless it is altered by an accidental in the music).
By first learning to construct major and minor scales, you have already learned to figure out what sharps or flats are in a given scale or KEY. The TONIC or KEYNOTE of a scale is the same as the name of the KEY in which it is the main scale. So if a song is based on the D MAJOR SCALE, it is said to be in the KEY of D MAJOR.
A typical KEY SIGNATURE with sharps looks like the one shown below on the grand staff. POINT YOUR MOUSE at each sharp to see which notes are affected by that sharp.

A sharp applies to all notes of that name regardless of the octave unless indicated otherwise in the music with an accidental.
A typical KEY SIGNATURE with flats looks like the one shown below on the grand staff. POINT YOUR MOUSE at each flat to see which notes are affected by that flat.

A flat applies to all notes of that name regardless of the octave unless indicated otherwise in the music with an accidental.