Control statements in C++ are used to control the flow of execution in a program. They allow you to make decisions, repeat blocks of code, and break out of loops. Understanding control statements is essential for writing efficient and readable code.
Conditional statements allow you to execute different blocks of code based on certain conditions. The most common conditional statements in C++ are:
Example of an if statement:
int x = 10;
if (x > 5) {
std::cout << "x is greater than 5" << std::endl;
}Loops are used to repeat a block of code multiple times until a certain condition is met. C++ supports several types of loops, including:
Example of a for loop:
for (int i = 0; i < 5; ++i) {
std::cout << "Value of i: " << i << std::endl;
}The switch statement is used to select one of many blocks of code to be executed. It is commonly used when you have a variable or expression with multiple possible values.
Example of a switch statement:
int day = 3;
switch (day) {
case 1:
std::cout << "Monday" << std::endl;
break;
case 2:
std::cout << "Tuesday" << std::endl;
break;
case 3:
std::cout << "Wednesday" << std::endl;
break;
// Add more cases as needed
default:
std::cout << "Invalid day" << std::endl;
}