In C++, the
switch statement is used to make decisions based on the value of a variable. It allows you to check multiple possible values for a variable and execute different code depending on which value it matches.Here's how the switch statement works:
- You have a variable (like an integer or character).
- The
switchchecks the value of that variable. - It compares the variable to a list of possible values (called cases).
- When it finds a match, it runs the code for that case.
- If none of the cases match, there’s an optional
defaultblock that can run.Basic Structure:
switch (variable) {
case value1:
// Code to run if variable is equal to value1
break;
case value2:
// Code to run if variable is equal to value2
break;
// You can add more cases here
default:
// Code to run if no case matches
}
Key points:
break: After each case, you should include abreakto stop theswitchfrom checking the other cases. Without it, all the code below the matching case will also run, even if it doesn't match.default: Thedefaultcase is optional. It will run only if none of the other cases match the variable.
Example:- #include <iostream>
- using namespace std;
- int main() {
- int day = 3;
- switch (day) {
- case 1:
- cout << "Monday";
- break;
- case 2:
- cout << "Tuesday";
- break;
- case 3:
- cout << "Wednesday";
- break;
- case 4:
- cout << "Thursday";
- break;
- default:
- cout << "Not a valid day";
- }
- return 0;
- }
summary:
Theswitchstatement in C++ is used to make decisions based on the value of a variable. It checks the variable against a list of possible values (called cases) and executes the corresponding code for the matching case. Thebreakstatement is used to stop further case checking after a match is found, and thedefaultblock (optional) runs if no case matches.


Thats great 👍
ReplyDeleteProud
ReplyDeleteSupport
ReplyDeleteWonderful , Belal keep going 💗
ReplyDeleteGoat 🐐
ReplyDeleteGreat
ReplyDeleteContinue
ReplyDelete