// A program to count the number of A's, B's etc entered as grades
// Uses a sentinel value of 'Z'
// file: ch3xmpl5.cpp
#include <iostream.h>
void main()
{
// Purpose: A program to count the number of A's, B's etc entered as grades
// Receives: NONE
// Returns: NONE
int numA = 0;
int numB = 0;
int numC = 0;
int numD = 0;
int numF = 0;
char letterGrade;
cout << "Please enter a letter grade (A, B, C, D or F)\n";
cout << "Enter a Z to exit\n";
cin >> letterGrade;
while ((letterGrade != 'Z') && (letterGrade != 'z'))
{ if ((letterGrade == 'A') || (letterGrade == 'a'))
{ numA++;
}
else // can't be an A
{ if ((letterGrade == 'B') || (letterGrade == 'b'))
{ numB++;
}
else // can't be an A or a B
{ if ((letterGrade == 'C') || (letterGrade == 'c'))
{ numC++;
}
else // can't be an A or a B or a C
{ if ((letterGrade == 'D') || (letterGrade == 'd'))
{ numD++;
}
else // can't be an A or a B or a C or a D
{ numF++; // assumes that only correct letters are entered
}
}
}
}
cout << "Please enter a letter grade (A, B, C, D or F)\n";
cout << "Enter a Z to exit\n";
cin >> letterGrade;
}
cout << " Grade Count\n";
cout << "A's \t\tB's \t\tC's \t\tD's \t\tF's";
cout << "\t\t" << numA << "\t\t" << numB << "\t\t" << numC
<< "\t\t" << numD << "\t\t" << numF;
}
The 'if' statements are relatively straight forward. For example, the first one says, "If the grade entered equals 'A' or 'a', add 1 to the number of A's." The end of loop test is a bit more complex. The loop should end when either a 'Z' or a 'z' is entered. Notice that the English uses an 'or' while the program uses the symbol for 'and'. The reason for this is that the English describes when the loop will end but the 'while' test determines if the loop will continue. In other words, the program tests for just the opposite of what the English descibes. You need to be careful of this when writing code. If you are told when a loop should end but the code itself checks to see if the loop should continue, you need to change the logical operator you are using.Mathematically this can be explained using what is called DeMorgan's Law:
Other points worth noting: