Control structures are essential components of programming languages that allow you to alter the flow of execution based on certain conditions. They help you make decisions, repeat code blocks, and create more dynamic and flexible programs.
Types of Control Structures
Decision-Making Structures:
if statement: Executes a block of code only if a specified condition is true.
if-else statement: Executes one block of code if a condition is true, and another block if it's false.
switch statement: Selects one of several code blocks to execute based on the value of an expression.
Looping Structures:
for loop: Executes a block of code a specified number of times.
while loop: Executes a block of code as long as a specified condition is true.
do-while loop: Executes a block of code at least once, and then continues to execute as long as a specified condition is true.
Examples
1. if statement:
C++
int age = 25;
if (age >= 18) {
cout << "You are eligible to vote." << endl;
}
2. if-else statement:
C++
int number = 10;
if (number % 2 == 0) {
cout << "The number is even." << endl;
} else {
cout << "The number is odd." << endl;
}
3. switch statement:
C++
char grade = 'A';
switch (grade) {
case 'A':
cout << "Excellent!" << endl;
break;
case 'B':
cout << "Very good!" << endl;
break;
case 'C':
cout << "Good!" << endl;
break;
default:
cout << "Invalid grade." << endl;
}
4. for loop:
C++
for (int i = 1; i <= 5; i++) {
cout << "Iteration " << i << endl;
}
5. while loop:
C++
int count = 1;
while (count <= 5) {
cout << "Count: " << count << endl;
count++;
}
6. do-while loop:
C++
int number = 0;
do {
cout << "Enter a positive number: ";
cin >> number;
} while (number <= 0);
cout << "You entered: " << number << endl;
By effectively using control structures, you can create more dynamic and flexible C++ programs that can handle various scenarios and make intelligent decisions.
Comentários