Switch Statement in C++
Switch in C++
Switch Statement is one of the statement that is used in conditional transfer of control. Like if statements it also has a conditional statement that compare the value & against it transfer control from one part to other part of program.
- The value of expression & case label both are in form of integer or character type not in double or float value otherwise compiler generate error..
- The break causes the rest of the switch case statement to be skipped. If we don't use break statement all the cases are compared and default case must execute it generate a logical error.
- The position of default label is not fixed. it may be placed before the first case statement or after last case.
- The switch statement is especially useful when the selection is based on the value.
Syntax:
switch ( condition/expression )
{
case val_1:
statement(s);
break;
case val_2:
statement(s);
break;
case val_3:
statement(s);
break;
case val_n:
statement(s);
break;
default:
statement(s);
break;
}
- When we want to use two case labels,one after the other, without any statement between them.This sort of arrangement of case labels work equivalent to the logical OR label.
case val_2:
statement(s);
break;
Statements are executed when the value are matched with anyone variable val_1 or val_2.
Example:
#include<iostream>
using namespace std;
void main()
{
char ch='A';
cout<<"Using Switch Statement"<<endl;
cout<<"Enter Alphabet:";
cin>>ch;
switch(ch)
{
case'a':
case'A':
cout<<ch<<" is Vowel....."<<endl;
break;
case'e':
case'E':
cout<<ch<<" is Vowel....."<<endl;
break;
case'i':
case'I':
cout<<ch<<" is Vowel....."<<endl;
break;
case'o':
case'O':
cout<<ch<<" is Vowel....."<<endl;
break;
case'u':
case'U':
cout<<ch<<" is Vowel....."<<endl;
break;
default:
cout<<ch<<" is Consonant....."<<endl;
break;
}
system("pause");
}
Comments
Post a Comment