Jan 11, 2012

Using Switch & break Statement

Using Switch & Break Statement

Switch statement is used instead of if statement using if statement multiple time can replace with switch and this make program short.
Break statement is used break that code proceed next like for loop i set to run 5 time and i write break it only run 1 time it skip braces part and continue to rest of code. Its used in loops and switch...


syntax of switch:
switch(variable)
{case 1 : statement
break;
case 2 : statement
break;
case 3 : statement
break;
...
...
default : statement
break;
}

Check the example:

#include<iostream.h>
#include<conio.h>
int main()
{char a;
//check the user input is vowel or not
cout << "Enter any character \n";
cin >>a;
switch(a) //no semi colon
{
case 'a':
case 'e':

case 'i':

case 'o':

case 'u':
case 'A':
case 'E':

case 'I':

case 'O':

case 'U': cout<<"Your input is Vowel\n";
break;

default : cout << "Your input is not vowel\n";
break;
}
/*
above i take input from user and under switch braces i write that variable here choice is made and it switch to according to that Case
like here if i enter a character then it goto switch(a) then it redirect to selected case like case 'a' then it print
'Your input is Vowel' 
if you enter anything z then it redirect to default that display  
'Your input is not vowel'
and break statement is necessary to differentiate cases that if you didn't write break then it execute all other cases after that like if i enter a then it also print your input is not vowel if i didn't set break
thats why i write only one time 
'Your input is Vowel'
and no break between them and in end i set break!!!
*/
getch();
return 0;
}


OUTPUT

 


0 comments:

Post a Comment