CS 1400 Jan 2007 Chapter 4, sections 1 - 6
Relational operators Less than< Greater than> Less than or equal<= Greater than or equal>= Equal== Not equal!=
Relational expressions A comparison is a relational expression A simple relational expression compares two operands and is either true or false Examples cost < 56 time >= != age
bool variables A bool variable can hold true or false Examples: bool answer, flag; answer = age < 25; flag = true; What is truth? In C++, true is non-zero, false is zero
Condition statements General forms if (expr) { statements } else { statements }
Condition statements… Each condition statement divides a program into two separate paths –the true path –the false path Only one of these two paths are taken!
Braces are not required for a single statement But an else is always associated with the closest possible if above it! Example: Skill level >1 is advanced, level >2 is advanced master, lower levels are beginners. if (skill > 1) cout << “advanced “; if (skill > 2) cout << “master”; else cout << “beginner”;
Solution – use braces! if (skill > 1) {cout << “advanced “; if (skill > 2) cout << “master”; } else cout << “beginner”;
Nested conditions (if/else/if) Example: Output a letter grade based upon a test score –90 to 100 is an A –80 to below 90 is a B –70 to below 80 is a C –60 to below 70 is a D –below 60 is an F Solution: Divide the program into two parts Stepwise Decomposition!
cout << “Enter grade: “; cin >> grade; if (grade >= 90) {cout << “A”; } else { } grade must be B or below First, the A’s and non A’s
Now divide the remainder two parts (B’s and non B’s) if (grade >= 80) {cout << “B”; } else { } grade must be C or below
and so on… if (grade >= 70) {cout << “C”; } else { } grade must be D or below
Finally, grade must be D or F if (grade >= 60) cout << “D”; else cout << “F”;
#include using namespace std; int main() {float grade; cout << "Enter grade: "; cin >> grade; if (grade >= 90) {cout << "A"; } else {if (grade >= 80) {cout << "B"; } else {if (grade >= 70) {cout << "C"; } else {if (grade >= 60) cout << "D"; else cout << "F"; }
#include using namespace std; int main() {float grade; cout << "Enter grade: "; cin >> grade; if (grade >= 90) cout << "A"; else if (grade >= 80) cout << "B"; else if (grade >= 70) cout << "C"; else if (grade >= 60) cout << "D"; else cout << "F"; } Braces are actually not needed for a single statement!