Friday, 9 March 2012

The Switch Statements in C++

Good Afternoon Readers,


Today we will discuss about the switch statement.
When defining an expression whose result would lead to a specific program execution, the switch statement considers that result and executes a statement based on the possible outcome of that expression, this possible outcome is called a case. The different outcomes are listed in the body of the switch statement and each case has its own execution, if necessary. The body of a switch statement is delimited from an opening to a closing curly brackets: “{“ to “}”. The syntax of the switch statement is:

       switch(Expression)
{
    case Choice1:
        Statement1;
    case Choice2:
        Statement2;
    case Choice-n:
        Statement-n;
}

The expression to examine is an integer. Since an enumeration (enum) and the character (char) data types are just other forms of integers, they can be used too. Here is an example of using the switch statement:
#include <iostream>
void main()
{
 int Number; 
 cout << "Type a number between 1 and 3: ";
 cin >> Number;
 switch (Number)
 {
 case 1:
  cout << "\nYou typed 1.";
 case 2:
  cout << "\nYou typed 2.";
 case 3:
  cout << "\nYou typed 3.";
 }
 getch();
}
The program above would request a number from the user. If the user types 1, it would execute the first, the second, and the third cases. If she types 2, the program would execute the second and third cases. If she supplies 3, only the third case would be considered. If the user types any other number, no case would execute.
When establishing the possible outcomes that the switch statement should consider, at times there will be other possibilities other than those listed and you will be likely to consider them. This special case is handled by the default keyword. The default case would be considered if none of the listed cases matches the supplied answer. The syntax of the switch statement that considers the default case would be:
switch(Expression)
{
    case Choice1:
        Statement1;
    case Choice2:
        Statement2;
    case Choice-n:
        Statement-n;
    default:
        Other-Possibility;
}

Therefore another version of the program above would be

#include <iostream>
void main()
{
 int Number;
 cout << "Type a number between 1 and 3: ";
 cin >> Number;
 switch (Number)
 {
 case 1:
  cout << "\nYou typed 1.";
 case 2:
  cout << "\nYou typed 2.";
 case 3:
  cout << "\nYou typed 3.";
 default:
  cout << endl << Number << " is out of the requested range.";
 }
 getch();
}

Thats all for now,Have a nice day.
Sidh.

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Web Hosting Coupons