08 - Conditional Statement
08 - Conditional Statement
Programming
Fundamentals
Decision Making
• If
• If-else
If-else • If-else if Switch
• Nested it
If Statement
if (condition) {
// block of code
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
Example of if statement
Example 1 Example 2
#include <iostream>
using namespace std;
int x = 20;
int main() { int y = 18;
if (20 > 18) { if (x > y) {
cout << "20 is greater than 18"; cout << "x is greater than y";
} }
return 0;
}
Else Statement
• Use the else statement to specify a block of
code to be executed if the condition is false.
• Syntax
if (condition) {
// block of code
else {
// block of code
#include <iostream>
using namespace std;
Example
int main() {
In the example above, time int time = 20;
(20) is greater than 18, so the
condition is false. Because of if (time < 18) {
this, we move on to the else cout << "Good day.";
condition and print to the
screen "Good evening". If the }
time was less than 18, the else {
program would print "Good cout << "Good evening.";
day".
}
return 0;
}
Else if Statement
Use the else if statement to specify a new condition if the first condition is false.
if (condition1) {
// block of code to be executed if condition1 is true
}
else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
}
else {
// block of code to be executed if the condition1 is false and condition2 is false
}
Flowchart
int time = 22;
Example if (time < 10) {
cout << "Good morning.";
In this example above, time (22)
is greater than 10, so the first
}
condition is false. else if (time < 20) {
The next condition, in the else if
statement, is also false, so we cout << "Good day.";
move on to the else condition
since condition1 and condition2
}
is both false - and print to the
screen "Good evening".
else {
However, if the time was 14, our cout << "Good evening.";
program would print "Good
day."
}
Nested if Statement
// Nested - if statement
// Will only be executed if statement above
// is true
if (i < 12)
cout<<"i is smaller than 12 too\n";
else
cout<<"i is greater than 15";
}
Shorthand if..else
There is also a short-hand if else, which is known as the ternary operator
because it consists of three operands. It can be used to replace multiple
lines of code with a single line. It is often used to replace simple if else
statements:
Else if
If Statement Else Statement
Statement
Shorthand
Nested if
Exercises if..else
Statement
Statement