lab manual-4
lab manual-4
Switch statement is C/C++ language is used for selection control. The difference
between if/else and switch selection statements is that the second one is used for
making a selection from multiple statements.
There are times when you'll find yourself writing a huge if block that consists of
many else if statements. The switch statement can help simplify things a little.
It allows you to test the value returned by a single expression and then execute
the relevant bit of code.
You can have as many cases as you want, including a default case which is
evaluated if all the cases fail. Let's look at the general form.
switch (expression)
{
case expression1:
/* one or more statements */
case expression2:
/* one or more statements */
/* ...more cases if necessary */
default:
/* do this if all other cases fail */
}
PROGRAMMING FUNDAMENTALS
#include <iostream>
using namespace std;
int main()
{
int a;
cin>>a;
switch (a) { case 1:
cout<<"You chose number 1\n";
case 2:
cout<<"You chose number 2\n"; case 3:
cout<<"You chose number 3\n"; case 4:
cout<<"You chose number 4\n"; default:
cout<<"That's not 1,2,3 or 4!\n"; You'll notice that the program will select the
} correct case but will also run through all the
return 0; cases below it (including the default) until the
} switch block's closing bracket is reached.
To prevent this from happening, we'll need to
insert another statement into our cases...
Break:
The break statement terminates the execution of the nearest enclosing switch statement in which
it appears. Control passes to the statement that follows the terminated statement
#include <iostream>
using namespace std;
int main()
{
int a;
cin>>a;
switch (a) { case 1:
cout<<"You chose number 1\n"; break;
case 2:
cout<<"You chose number 2\n"; break;
case 3:
cout<<"You chose number 3\n"; break;
case 4:
cout<<"You chose number 4\n"; break;
default:
cout<<"That's not 1,2,3 or 4!\n";}
return 0;
}
PROGRAMMING FUNDAMENTALS