in my lasrt article i told you about function in c++ now this time to know what is switch in c++
Actually Switch case statements are a substitute for long if statements that compare a variable to several "integral" values.
lets see what is integral value ??
"integral" values are simply values that can be expressed as an integer, such as the value of a char.
The value of the variable given into switch is compared to the value following each of the cases, and when one value matches the value of the variable, the computer continues executing the program from that point.
know how we write case
Switch statements serves as a simple way to write long if statements when the requirements are met
here default case is optional, but you can write it as it handles any unexpected cases
let us see by example by which you can know how will use switch case in your program
Actually Switch case statements are a substitute for long if statements that compare a variable to several "integral" values.
lets see what is integral value ??
"integral" values are simply values that can be expressed as an integer, such as the value of a char.
The value of the variable given into switch is compared to the value following each of the cases, and when one value matches the value of the variable, the computer continues executing the program from that point.
know how we write case
int a = 20;
int b = 30;
int c = 20;
switch ( a ) {
case b:
// Code
break;
case c:
// Code
break;
default:
// Code
break;
}
Switch statements serves as a simple way to write long if statements when the requirements are met
here default case is optional, but you can write it as it handles any unexpected cases
let us see by example by which you can know how will use switch case in your program
#include <iostream>
void playgame()
{
cout << "Play game called";
}
void loadgame()
{
cout << "Load game called";
}
void playmultiplayer()
{
cout << "Play multiplayer game called";
}
int main()
{
int input;
cout<<"1. Play game\n";
cout<<"2. Load game\n";
cout<<"3. Play multiplayer\n";
cout<<"4. Exit\n";
cout<<"Selection: ";
cin>> input;
switch ( input ) {
case 1: // Note the colon, not a semicolon
playgame();
break;
case 2: // Note the colon, not a semicolon
loadgame();
break;
case 3: // Note the colon, not a semicolon
playmultiplayer();
break;
case 4: // Note the colon, not a semicolon
cout<<"Thank you for playing!\n";
break;
default: // Note the colon, not a semicolon
cout<<"Error, bad input, quitting\n";
break;
}
cin.get();
}
if you have any question about it feel free to ask
No comments:
Post a Comment