Control Flow Statements
Control flow statements in C++ allow us to control the execution flow of our program based on conditions and perform repetitive tasks.
Loops
Loops are used to repeat a block of code multiple times. The most commonly used loop structures in C++ are:
- for loop: Executes a block of code a specified number of times. Here's an example:
TEXT/X-C++SRC
1for (int i = 0; i < 5; i++) {
2 cout << "Iteration " << i+1 << endl;
3}
- while loop: Executes a block of code as long as a specified condition is true.
- do-while loop: Similar to the while loop, but it guarantees that the code is executed at least once before checking the condition.
Conditionals
Conditionals allow us to execute different blocks of code based on specified conditions. The most commonly used conditional structures in C++ are:
- if statement: Executes a block of code if a condition is true. Here's an example:
TEXT/X-C++SRC
1int age = 30;
2if (age >= 18) {
3 cout << "You are an adult" << endl;
4} else {
5 cout << "You are a minor" << endl;
6}
- else statement: Executes a block of code if the condition of the if statement is false.
- else if statement: Allows us to specify additional conditions to check.
Switch Statements
Switch statements allow us to select one of many code blocks to be executed based on the value of a variable. Here's an example:
TEXT/X-C++SRC
1int choice = 2;
2switch (choice) {
3 case 1:
4 cout << "You chose option 1" << endl;
5 break;
6 case 2:
7 cout << "You chose option 2" << endl;
8 break;
9 default:
10 cout << "Invalid choice" << endl;
11 break;
12}
Feel free to experiment with loops, conditionals, and switch statements in C++. These control flow statements are essential for implementing complex logic and creating efficient algorithms.
xxxxxxxxxx
33
}
using namespace std;
int main() {
// Loop example
for (int i = 0; i < 5; i++) {
cout << "Iteration " << i+1 << endl;
}
// Conditional example
int age = 30;
if (age >= 18) {
cout << "You are an adult" << endl;
} else {
cout << "You are a minor" << endl;
}
// Switch statement example
int choice = 2;
switch (choice) {
case 1:
cout << "You chose option 1" << endl;
break;
case 2:
cout << "You chose option 2" << endl;
break;
default:
cout << "Invalid choice" << endl;
break;
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment