CMPE 011 - Module 3-Flow Control - Conditions and If Statements
CMPE 011 - Module 3-Flow Control - Conditions and If Statements
%= x %= 3 x=x%3
Arithmetic Operators
Operators used to perform common &= x &= 3 x=x&3
mathematical operations. |= x |= 3 x=x|3
OPERATOR Name Description Example
^= x ^= 3 x=x^3
+ Addition Adds together two x+y
values >>= x >>= 3 x = x >> 3
1
A list of all comparison operators:
if to specify a block of code to be
executed, if a specified condition is true
OPERATOR Name Example
else to specify a block of code to be
== Equal to x == y
executed, if the same condition is false
!= Not equal x != y
else if to specify a new condition to test, if the
> Greater than x>y first condition is false
< Less than x<y to specify many alternative blocks of
switch
>= Greater than or equal x >= y code to be executed
to
2
int time = 20; The Short Hand If…Else (Ternary Operator)
if (time < 18) { There is also a short-hand if else, which is known
cout << "Good day."; as the ternary operator because it consists of three
} else {
cout << "Good evening."; operands. It can be used to replace multiple lines of code
} with a single line. It is often used to replace simple if else
// Outputs "Good evening." statements:
In the example above, time (20) is greater than 18, so the variable = (condition) ? expressionTrue :
condition is false. Because of this, we move on to the else expressionFalse;
condition and print to the screen "Good evening". If the time
was less than 18, the program would print "Good day".
Instead of writing:
The else if Statement int time = 20;
Use the else if statement to specify a new condition if the if (time < 18) {
first condition is false. cout << "Good day.";
} else {
cout << "Good evening.";
if (condition1) { }
// block of code to be executed if
condition1 is true
} else if (condition2) { You can simply write:
// block of code to be executed if the
int time = 20;
condition1 is false and condition2 is true
string result = (time < 18) ? "Good day."
} else {
: "Good evening.";
// block of code to be executed if the
cout << result;
condition1 is false and condition2 is
false
}
Example explained
● In the example above, time (22) is greater than 10,
so the first condition is false. The next condition, in
the else if statement, is also false, so we move on to
the else condition since condition1 and condition2
is both false - and print to the screen "Good
evening".
● However, if the time was 14, our program would
print "Good day."
3
SOURCES:
● https://www.w3schools.com/cpp/cpp_operator
s.asp