Control structure: if / else

In this example, we assign the letter grade to a variable. Notice that letter is char (character). Characters are single letters. Use double quotes to enclose strings, but single quotes to enclose characters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Print the letter grade
#include <iostream>
using namespace std;
int main() { 
  int grade;
  char letter;
  cout<<"Enter your numeric grade:";
  cin>>grade;
  if (grade < 65) letter='F';
  else if (grade < 70) letter='D';
  else if (grade < 80) letter='C';
  else if (grade < 90) letter='B';
  else letter='A';
  cout<<"The letter grade is "<<letter<<"\n";
  system("pause");
  return 0;
} //main
CODE

One advantage of assigning the value to a variable is that we have just one cout statement. If we need to change the way the grade is displayed, we only have to change 1 statement.

NEXT: Test if a number is a valid month