Lesson 4 of 19
Conditionals
Conditionals in C++
C++ conditionals work the same as in C: if, else if, else, and the ternary operator.
if / else if / else
int temperature = 25;
if (temperature > 30) {
cout << "Hot" << endl;
} else if (temperature > 20) {
cout << "Warm" << endl;
} else if (temperature > 10) {
cout << "Cool" << endl;
} else {
cout << "Cold" << endl;
}
Comparing Strings
With C++ string, you can use == directly:
string color = "red";
if (color == "red") {
cout << "Stop" << endl;
} else if (color == "green") {
cout << "Go" << endl;
}
Ternary Operator
A compact one-line conditional:
int x = 10;
string result = (x > 0) ? "positive" : "non-positive";
cout << result << endl;
Logical Operators
| Operator | Meaning |
|---|---|
&& | AND |
| ` | |
! | NOT |
int age = 25;
bool hasID = true;
if (age >= 18 && hasID) {
cout << "Welcome" << endl;
}
Your Task
Given a score of 85:
- Print the score
- Assign a letter grade (A ≥ 90, B ≥ 80, C ≥ 70, otherwise F)
- Print the grade
JSCPP loading...
Loading...
Click "Run" to execute your code.