C++ Control Flow (if, switch) Tutorial
Control flow statements like if and switch allow you to execute different code paths based on conditions in your program.
1. The if Statement
Use the if statement to execute code conditionally:
#include <iostream>
using namespace std;
int main() {
int number = 10;
if (number > 5) {
cout << "Number is greater than 5." << endl;
} else {
cout << "Number is 5 or less." << endl;
}
return 0;
}
In this example, the program checks if number is greater than 5 and outputs the corresponding message.
2. The switch Statement
The switch statement executes code blocks based on specific case values:
#include <iostream>
using namespace std;
int main() {
int choice = 2;
switch (choice) {
case 1:
cout << "You selected option 1." << endl;
break;
case 2:
cout << "You selected option 2." << endl;
break;
default:
cout << "Invalid selection." << endl;
}
return 0;
}
In this example, the program executes code based on the value of choice.
3. Nested and Combined Statements
You can combine and nest if and switch statements for more complex conditions:
if (condition1) {
if (condition2) {
// Nested if
} else {
// Else block
}
}
switch (variable) {
case 1:
if (condition3) {
// Combined with if
}
break;
}
Be careful to maintain readability when nesting and combining statements.
4. Best Practices
- Use
iffor general conditions andswitchfor fixed values. - Always include a
defaultcase in aswitchfor unexpected values. - Maintain proper indentation for readability.
5. Next Steps
Explore loops and functions to add more functionality to your C++ programs!
×