4. Control Structures#
As with all other procedural-based programming languages, C++ has statements for making decisions and repeating code.
4.1. if statement#
We use the if
statement to execute a code block when a specified condition evaluates to true. The basic syntax:
if (condition) {
codeblock
}
int age = 17;
if (age >= 16) {
cout << "You are old enough to drive in most US states.\n";
}
C++ does have an optional else
keyword that executes when the condition is false.
1//filename: if.cpp
2//complile: g++ -std=c++17 -o if if.cpp
3//execute: ./if
4#include <iostream>
5using std::cout;
6using std::endl;
7
8int main() {
9 int age = 15;
10 if (age >= 16) {
11 cout << "You can drive!\n";
12 cout << "You need a license first, though...\n";
13 }
14 else {
15 cout << "You are not old enough to drive.\n";
16 cout << "You will need to wait until you are 16.\n";
17 }
18}
If you have several conditions that you need to evaluate in order, you can use an if else if
statement. As with the if
statement, you can have an optional else
portion at the end of the statement. C++ evaluates these if clauses in their listed order.
1//filename: ifelse.cpp
2//complile: g++ -std=c++17 -o ifelse ifelse.cpp
3//execute: ./ifelse
4#include <iostream>
5using std::cout;
6using std::endl;
7
8int main() {
9 int grade = 78;
10
11 if (grade >= 90) {
12 cout << "A\n";
13 }
14 else if (grade >= 80) {
15 cout << "B\n";
16 }
17 else if (grade >= 70) {
18 cout << "C\n";
19 }
20 else if (grade >= 60) {
21 cout << "D\n";
22 }
23 else {
24 cout << "F\n";
25 }
26}
4.1.1. Nested Ifs#
As code blocks can contain any C++ statement or expression, if
statements can be nested.
Run the following code block several times, changing the salary
, commute_time_min
, and free_coffee
values to see how the logic works. You should be able to produce each of the four different outputs.
1//filename: take_job.cpp
2//complile: g++ -std=c++17 -o take_job take_job.cpp
3//execute: ./take_job
4#include <iostream>
5using std::cout;
6using std::endl;
7
8int main() {
9 int salary = 60000;
10 int commute_time_min = 30;
11 int free_coffee = 0;
12
13 if (salary > 50000) {
14 if (commute_time_min < 60) {
15 if (free_coffee) {
16 cout << "Cool. I'm going to like this job.\n";
17 } else {
18 cout << "Close location and I like the salary, but I NEED coffee.\n";
19 }
20 } else {
21 cout << "I don't want to drive that far.\n";
22 }
23 } else {
24 cout << "I'm worth more than that.\n";
25 }
26}
4.2. Switch#
Rather than relying upon multiple if else
statements, C++ offers the switch
statement as an alternative when a single variable is repeatedly evaluated. Each value is called a case.
The switch statement follows the following syntax:
switch(expression) {
case constant-expression: statements;
break;
case constant-expression: statements;
break
default: statements;
break;
}
The following rules apply to a switch
statement −
The expression be an intergral or an enumeration type.
The switch statement can have any number of case statements. Each case contains a constant/literal value to compare the expression to with equality. The literal value (constant-expression) must be the same data type
When a match is found (equality), the statements following that case will execute until a break statement is reached.
The constant-expresssions must be unique.
Similar to breaks in Python, a break statement causes the flow of control to jump to the next line following the switch statement.
break is optional for a case statement.If the break does not appear, then the flow of control falls through to subsequent cases until a break is reached. Often, multiple cases can be expressed together. If you do have statement(s), then you should place a comment /* fall through */ to let others explicitly know the fall through is intentional. Not having a break statement can be a common issue with switch statements.
A switch statement can have an optional default case. The case must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case as it’s the last “case” and the flow of control passes through the end of the switch statement.
1//filename: switch.cpp
2//complile: g++ -std=c++17 -o switch switch.cpp
3//execute: ./switch
4#include <iostream>
5using std::cout;
6using std::endl;
7
8int main() {
9 char suite = 'H';
10 switch(suite) {
11 case 'C': cout << "Clubs\n"; break;
12 case 'D': cout << "Diamonds\n"; break;
13 case 'H': cout << "Hearts\n"; /* fall through */
14 case 'S': cout << "Spades\n"; break;
15 default: cout << "Unknown suite: " << suite << "\n";
16 }
17}
Here’s another example of a switch statement.
1//filename: calc.cpp
2//complile: g++ -std=c++17 -o calc calc.cpp
3//execute: ./calc
4#include <iostream>
5using std::cout;
6using std::endl;
7
8int main(int argc, char *argv[]) {
9 char operation;
10 double n1, n2;
11
12 cout << "Enter a math operation such as 5 + 2: ";
13 std::cin >> n1 >> operation >> n2;
14 if (std::cin.fail()) { // Checks in the input succeeded or not ..
15 std::cerr << "Failed to read the math operation" << "\n";
16 return EXIT_FAILURE;
17 }
18
19 switch(operation) {
20 case '+':
21 cout << n1 << " + " << n2 << " = " << n1 + n2 << "\n";
22 break;
23
24 case '-':
25 cout << n1 << " - " << n2 << " = " << n1 - n2 << "\n";
26 break;
27
28 case '*':
29 cout << n1 << " * " << n2 << " = " << n1 * n2 << "\n";
30 break;
31
32 case '/':
33 cout << n1 << " / " << n2 << " = " << n1 / n2 << "\n";
34 break;
35
36 // operator doesn't match any case constant +, -, *, /
37 default:
38 std::cerr << "Error! operator is not correct: " << operation << "\n";
39 }
40
41 return EXIT_SUCCESS;
42}
4.3. Iteration#
As with Python, C++ has several statements to perform repetitive tasks.
4.3.1. for loop#
To support definite loops (when the code block executes a fixed number of times, usually based upon a counter, C has for
loop. The syntax, though, differs from Python’s for loop.
for (initializer; condition; update) {
for_loop_body
}
The for
loop works by first executing the expression statement in the initializer clause. Typically, this is used to set a loop counter variable to it’s starting value such as int i = 0
. Next, the condition is evaluated to see if the loop should be entered. Typically, this is a comparison against the end of the number of items to process. Then the for loop body executes. This consists of one or more statements. Then then the update statement executes. Typically, this updates the counter variable such as i++
. The process then repeats with evaluating the condition. The following flowchart demonstrates this process:
The following demonstrates a for
loop, printing the first 5 odd numbers to the console.
1//filename: for.cpp
2//complile: g++ -std=c++17 -o for for.cpp
3//execute: ./for
4#include <iostream>
5using std::cout;
6using std::endl;
7
8int main(int argc, char *argv[]) {
9 for (int i=0; i < 10; i++) {
10 if (i % 2 == 1) {
11 cout << i << "\n";
12 }
13 }
14 return 0;
15}
It is possible to leave one or more of the three portions of the for-loop empty. If the condition expression is empty, it automatically evaluates to true (1). A common idiom to create infinite loops is -
for(;;) {
code_block;
}
4.3.2. Indefinite Loops#
Similar to Python, C++ has the while
loop to repeat a code block as long as a given condition remains true.
while (condition) {
statement(s);
}
1//filename: while.cpp
2//complile: g++ -std=c++17 -o while while.cpp
3//execute: ./while
4#include <iostream>
5using std::cout;
6
7int main() {
8 int i = 1;
9 while (i < 6) {
10 cout << i << "\n";
11 i++;
12 }
13 return EXIT_SUCCESS;
14}
C++ also has a do-while
loop that evaluates the condition at the end of the loop. This allows the code block to execute at least once.
do {
statement(s);
} while (condition);
1//filename: dowhile.cpp
2//complile: g++ -std=c++17 -o dowhile dowhile.cpp
3//execute: ./dowhile
4#include <iostream>
5using std::cout;
6
7int main() {
8 int i = 1;
9 do {
10 cout << i << "\n";
11 i++;
12 } while (i < 1);
13 return 0;
14}
4.3.3. Break / Continue#
As with Python, C++ supports both the break
and continue
statements.
1//filename: break.cpp
2//complile: g++ -std=c++17 -o break break.cpp
3//execute: ./break
4#include <iostream>
5using std::cout;
6
7
8int main(int argc, char *argv[]) {
9 int i = 1;
10 while (i < 6) {
11 if (i % 3 == 0) {
12 break;
13 } else {
14 cout << i << "\n";
15 i++;
16 }
17 }
18 cout << "After the while loop" << "\n";
19
20 return 0;
21}
1//filename: continue.cpp
2//complile: g++ -std=c++17 -o continue continue.cpp
3//execute: ./continue
4#include <iostream>
5using std::cout;
6
7int main(int argc, char *argv[]) {
8 int i = 1;
9 while (i < 6) {
10 if (i % 2 == 0) {
11 i++;
12 continue;
13 } else {
14 cout << i << "\n";
15 i++;
16 }
17 }
18 cout << "After the while loop" << "\n";
19
20 return 0;
21}