Selection Statements in C ++
In C++, selection statements are used to control the flow of execution based on certain conditions. Here's a breakdown of the most common ones:
1. if statement
* Basic Structure:
if (condition) {
// Code to be executed if the condition is true
}
* Example:
int age = 25;
if (age >= 18) {
cout << "You are an adult." << endl;
}
* if...else statement:
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
* Example:
int number = 10;
if (number % 2 == 0) {
cout << "The number is even." << endl;
} else {
cout << "The number is odd." << endl;
}
* if...else if...else statement:
if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition1 is false and condition2 is true
} else {
// Code to be executed if neither condition1 nor condition2 is true
}
* Example:
int score = 75;
if (score >= 90) {
cout << "Grade: A" << endl;
} else if (score >= 80) {
cout << "Grade: B" << endl;
} else if (score >= 70) {
cout << "Grade: C" << endl;
} else {
cout << "Grade: F" << endl;
}
2. switch statement
* Used when you have multiple possible values for a single variable.
* Structure:
switch (expression) {
case value1:
// Code to be executed if expression equals value1
break;
case value2:
// Code to be executed if expression equals value2
break;
// ... more cases
default:
// Code to be executed if none of the cases match
}
* Example:
int dayOfWeek = 3;
switch (dayOfWeek) {
case 1:
cout << "Monday" << endl;
break;
case 2:
cout << "Tuesday" << endl;
break;
case 3:
cout << "Wednesday" << endl;
break;
// ... other days of the week
default:
cout << "Invalid day of the week." << endl;
}
Key Points:
* break statement: Essential within switch cases to prevent "fall-through" (where execution continues to the next case even if the current case matches).
* default case: Optional, but recommended for handling unexpected values.
* switch statement is often more efficient than a series of if...else if statements when dealing with multiple comparisons of the same variable.
Comments
Post a Comment