Download presentation
Presentation is loading. Please wait.
1
CS 1400 Jan 2007 Chapter 4, sections 1 - 6
2
Relational operators Less than< Greater than> Less than or equal<= Greater than or equal>= Equal== Not equal!=
3
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 >= 1.5 25 != age
4
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
5
Condition statements General forms if (expr) { statements } else { statements }
6
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!
7
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”;
8
Solution – use braces! if (skill > 1) {cout << “advanced “; if (skill > 2) cout << “master”; } else cout << “beginner”;
9
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!
10
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
11
Now divide the remainder two parts (B’s and non B’s) if (grade >= 80) {cout << “B”; } else { } grade must be C or below
12
and so on… if (grade >= 70) {cout << “C”; } else { } grade must be D or below
13
Finally, grade must be D or F if (grade >= 60) cout << “D”; else cout << “F”;
14
#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"; }
15
#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!
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.