Control Structures
Control structures allow you to control the flow of a program by making decisions and repeating certain tasks. In C++, there are several control structures that you can use:
- if-else statements: These statements are used to execute a block of code based on a specified condition. You can use the
if
keyword to specify the condition, and theelse
keyword to specify the code to be executed if the condition is false.
TEXT/X-C++SRC
1#include <iostream>
2
3int main() {
4 int age = 20;
5
6 if (age >= 18) {
7 std::cout << "You are an adult." << std::endl;
8 } else {
9 std::cout << "You are a minor." << std::endl;
10 }
11
12 return 0;
13}
- loops: Loops allow you to repeatedly execute a block of code until a certain condition is met. There are three types of loops in C++:
while
loop: Executes a block of code repeatedly as long as a specified condition is true.for
loop: Executes a block of code a specified number of times.do-while
loop: Executes a block of code first, and then repeats the execution as long as a specified condition is true.
TEXT/X-C++SRC
1#include <iostream>
2
3int main() {
4 // while loop
5 int i = 0;
6 while (i < 5) {
7 std::cout << i << std::endl;
8 i++;
9 }
10
11 // for loop
12 for (int j = 0; j < 5; j++) {
13 std::cout << j << std::endl;
14 }
15
16 // do-while loop
17 int k = 0;
18 do {
19 std::cout << k << std::endl;
20 k++;
21 } while (k < 5);
22
23 return 0;
24}
- switch statements: Switch statements allow you to perform different actions based on different conditions. You can specify multiple case statements, each with a different value, and the code within the matching case statement will be executed.
TEXT/X-C++SRC
1#include <iostream>
2
3int main() {
4 int day = 4;
5
6 switch (day) {
7 case 1:
8 std::cout << "Monday" << std::endl;
9 break;
10 case 2:
11 std::cout << "Tuesday" << std::endl;
12 break;
13 case 3:
14 std::cout << "Wednesday" << std::endl;
15 break;
16 case 4:
17 std::cout << "Thursday" << std::endl;
18 break;
19 case 5:
20 std::cout << "Friday" << std::endl;
21 break;
22 default:
23 std::cout << "Weekend" << std::endl;
24 }
25
26 return 0;
27}