CMPE 011 - Module 3-Flow Control - Conditions and If Statements
CMPE 011 - Module 3-Flow Control - Conditions and If Statements
In the
example below, we use the assignment operator (=) to
SUB-TOPIC
assign the value 10 to a variable called x:
SUB-SUB-TOPIC
int x = 10;
I. Operators
Operators are used to perform operations on The addition assignment operator (+=) adds a
variables and values. In the example below, we use value to a variable:
the + operator to add together two values:
int x = 10;
x += 5;
int x = 100 + 50;
Although the + operator is often used to add
together two values, like in the example above, it can A list of all assignment operators:
also be used to add together a variable and a value, or a
variable and another variable: OPERATOR Example Same As
= x=5 x=5
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250) += x += 3 x=x+3
int sum3 = sum2 + sum2; // 800 (400 + 400)
-= x -= 3 x=x-3
1
== Equal to x == y else if to specify a new condition to test, if the
first condition is false
!= Not equal x != y
Examples:
Comparison Operators Test two values to find out if 20 is greater than 18. If the
Logical operators are used to determine the condition is true, print some text:
logic between variables or values:
if (20 > 18) {
cout << "20 is greater than 18";
OPERATOR Name Description Example }
2
In the example above, time (20) is greater than 18, so the
expressionFalse;
condition is false. Because of this, we move on to the else
condition and print to the screen "Good evening". If the time
was less than 18, the program would print "Good day". Instead of writing:
int time = 20;
The else if Statement if (time < 18) {
Use the else if statement to specify a new condition if the cout << "Good day.";
first condition is false. } else {
cout << "Good evening.";
}
if (condition1) {
// block of code to be executed if
condition1 is true You can simply write:
} else if (condition2) {
// 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