Control Structure
1. Conditional Statements:
a. if Statement:
#include <iostream>
int main() {
int x = 10;
if (x > 5) {
std::cout << "x is greater than 5." << std::endl;
}
return 0;
}
The if statement allows you to execute a block of code only if a certain condition is true.
b. else if Statement:
#include <iostream>
int main() {
int x = 10;
if (x > 15) {
std::cout << "x is greater than 15." << std::endl;
} else if (x > 10) {
std::cout << "x is greater than 10." << std::endl;
} else {
std::cout << "x is 10 or less." << std::endl;
}
return 0;
}
The else if statement allows you to test multiple conditions in sequence.
2. Looping Statements:
a. for Loop:
#include <iostream>
int main() {
for (int i = 0; i < 5; ++i) {
std::cout << "Iteration " << i + 1 << std::endl;
}
return 0;
}
The for loop allows you to repeatedly execute a block of code a specified number of times.
b. while Loop:
#include <iostream>
int main() {
int count = 0;
while (count < 5) {
std::cout << "Count: " << count << std::endl;
++count;
}
return 0;
}
The while loop repeatedly executes a block of code as long as a specified condition is true.
c. do-while Loop:
#include <iostream>
int main() {
int count = 0;
do {
std::cout << "Count: " << count << std::endl;
++count;
} while (count < 5);
return 0;
}
The do-while loop is similar to the while loop, but it guarantees that the block of code is executed at least once, even if the condition is false initially.
3. Switch Statement:
#include <iostream>
int main() {
int choice = 2;
switch (choice) {
case 1:
std::cout << "Option 1 selected." << std::endl;
break;
case 2:
std::cout << "Option 2 selected." << std::endl;
break;
case 3:
std::cout << "Option 3 selected." << std::endl;
break;
default:
std::cout << "Invalid choice." << std::endl;
}
return 0;
}
The switch statement allows you to choose between many different options based on the value of an expression.
These control structures provide you with the flexibility to make decisions and repeat tasks based on conditions, allowing your programs to respond dynamically to different scenarios.