Decision Making
Decision Making
You already know that C++ supports the usual logical conditions from
mathematics:
You can use these conditions to perform different actions for different
decisions.
The if Statement
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
In the example below, we test two values to find out if 20 is greater than
18. If the condition is true, print some text:
Example
if (20 > 18) {
cout << "20 is greater than 18";
}
Example
int x = 201;
int y = 18;
if (x > y) {
cout << "x is greater than y";
}
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
else {
// block of code to be executed if the condition is false
}
Example
int time = 24;
if (time < 18) {
cout << "Good day.";
}
else {
cout << "Good evening.";
}
// Outputs "Good evening."
The else if Statement
Use the else if statement to specify a new condition if the first condition
is false.
Syntax
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
}
Example
int time = 22;
if (time < 10) {
cout << "Good morning.";
}
else if (time < 18) {
cout << "Good day.";
}
else {
cout << "Good evening.";
}
// Outputs "Good evening."
Instead of writing:
Example
int time = 20;
if (time < 18) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
Example
int time = 20;
string result = (time < 18) ? "Good day." : "Good evening.";
cout << result;
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
The example below uses the weekday number to calculate the weekday
name:
Example
int day = 2;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
}
// Outputs "Thursday" (day 4)
When C++ reaches a break keyword, it breaks out of the switch block.
This will stop the execution of more code and case testing inside the
block.
When a match is found, and the job is done, it's time for a break. There is
no need for more testing.
Example
int day = 4;
switch (day) {
case 6:
cout << "Today is Saturday";
break;
case 7:
cout << "Today is Sunday";
break;
default:
cout << "Looking forward to the Weekend";
}
// Outputs "Looking forward to the Weekend"