Switch statement in C++ programming allows you to control and execute the specific block of code among many alternatives, otherwise, execute the default block.
switch(integer expression)
{
case constant 1:
do this;
case constant 2:
do this;
case constant 3:
do this;
default:
do this;
}
#include<iostream.h>
#include<conio.h>
void main()
{
int i = 2;
switch(i) //switching on 'i' value.
{
case 1: //if 'i' have 1 then
cout<<"I am in case 1"<<endl; //print this and
break; //break the statement.
case 2: //if 'i' have 2 then
cout<<"I am in case 2"<<endl; //print this and
break; //break the statement.
case 3: //if 'i' have 3 then
cout<<"I am in case 3"<<endl; //print this and
break; //break the statement.
default: //if not in above then
cout<<"I am in default"<<endl; //print this.
}
getch();
}
#include<iostream.h>
#include<conio.h>
void main()
{
char c = 'x'; //assigning 'x' to 'c'.
switch(c) //switching on 'c' value.
{
case 'v': //if 'c' have 'v' have then
cout<<"I am in case v"<<endl; //print this and
break; //break the statement.
case 'a': //if 'c' have 'a' have then
cout<<"I am in case a"<<endl; //print this and
break; //break the statement.
case 'x': //if 'c' have 'x' have then
cout<<"I am in case x"<<endl; //print this and
break; //break the statement.
default: //if not in above then
cout<<"I am in default"; //print this.
}
getch();
}
#include<iostream.h>
#include<conio.h>
void main()
{
char ch;
cout<<"Enter any of the alphabet a, b, or c: ";
cin>>ch; //user enter value storing in 'ch'.
switch(ch) //switching on 'ch' value.
{
case 'a': //if 'ch' have 'a' Or
case 'A': //'A' value then
cout<<"a as in ashar"; //print this and
break; //break the statement.
case 'b': //if 'ch' have 'b' Or
case 'B': //'B' value then
cout<<"b as in brain"; //print this and
break; //break the statement.
case 'c': //if 'ch' have 'c' Or
case 'C': //'C' value then
cout<<"c as in cookie"; //print this and
break; //break the statement.
default: //if not in above then
cout<<"wish you knew what are alphabets"; //print this.
}
getch();
}