Can any one give an example of a switch?
Printable View
Can any one give an example of a switch?
if number is 1 the DoSomething will be called. if number is 2 then DoSomethingElse will be called followed by DoEndOfWorld. if number is 666 then DoEndOfWorld is called. If number is anything else "not valid" gets printed.Code:int number;
cin>>number;
switch(number)
{
case 1: DoSomething();
break;
case 2: DoSomethingElse();
case 666: DoEndOfWorld();
break;
default: cout<<"Not Valid";
}
I assume that you're talking about switch statements.
The keyword break must be included if you want to "break" out of the switch statement. If a number is entered that is not in the range 1-5, then the default statement is executed.Code:#include <iostream>
using std::cout;
using std::cin;
int main()
{
int x;
cout << "Enter a number from 1 - 5 : ";
cin >> x;
switch( x )
{
case 1: cout << "\nYou are dumb!"; break;
case 2: cout << "\nYou are average!"; break;
case 3: cout << "\nYou are clever!"; break;
case 4: cout << "\nYou are very clever!"; break;
case 5: cout << "\nYou are a genius!"; break;
default: cout << "\nYou are really dumb!"; break;
}
return 0;
}