All lessons
LESSON 12/53Making Decisions
Combining Conditions
GOALCheck two or more conditions at once.

Comparisons: == equal, != not equal, < > <= >=. Join them with && (and) or || (or).
ON THIS PAGE
SHOW EXAMPLE IN
//THE EXAMPLE
main.cpp
#include <iostream>
using namespace std;
int main() {
int age = 14;
bool hasTicket = true;
if (age >= 12 && hasTicket) {
cout << "You may enter" << endl;
}
if (age < 6 || age > 65) {
cout << "Free entry" << endl;
} else {
cout << "Pay full price" << endl;
}
return 0;
}> what you see
You may enter Pay full price
//LINE BY LINE
Watch it run
Every comparison ends up as a single value: true or false.
Comparison operators
| Operator | Meaning |
|---|---|
== | тэнцүү юу? / is equal to? |
!= | тэнцүү биш юү? / is not equal to? |
< · > | бага / их |
<= · >= | бага буюу тэнцүү / их буюу тэнцүү |
= assigns, == compares. if (x = 5) puts 5 into x instead of testing it, and is always true.
Combining conditions: &&, ||, !
| Operator | True when |
|---|---|
a && b | хоёулаа үнэн / both are true |
a || b | ядаж нэг нь үнэн / at least one is true |
!a | a худал бол / a is false |
if (age >= 13 && age <= 19) cout << "teenager";
if (day == 6 || day == 7) cout << "weekend";
if (!finished) cout << "still working";You cannot write if (13 <= age <= 19) in C++ the way you would in maths. Split it into two tests joined by &&.
Short-circuiting
If the left side of && is false, the right side is never checked. Same for || when the left side is true. This can protect you.
if (n != 0 && total / n > 5) { … }
// ↑ n тэг бол хуваалт хийгдэхгүй — 0-д хуваахаас сэргийллээ