Topic :Switch Statement in C++ Programming Language:

Switch Statement:

The switch statement, also known as Multiple-choice statements allow our program to choose from several alternatives. A switch Statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on it's for each case.



switch statement

As shown in above figure, the Switch Expression is an Expression that produce an case integral or enumerated type. The Switch compares the result of "Switch Expression" to each integral value of a case. if it finds a match, the corresponding statement of that case will execute. if it did not find a match in the first case, then the switch will try next and so on. if no match occurs, the default statement executes.

Did you Notice in the picture the every case end with a Break which causes execution to jump to the end of the switch body ( the Closing brace that completes the switch ). This is the conventional way to build a switch statement, but the break is optional. if it is missing, our CASE drops through to the one after it. That is, the code for the following case statements execute until a break is encountered. Although we don't usually want this kind of behavior, it can be useful to an experienced programmer.





Syntax:

The Syntax for a Switch statement in C++ is as follows:



Switch(expression)
{
	case 1:    //constant expression:
	statement; //Statement or Group of statement to execute:
	break;     //Optional
 
	case 2:    //constant expression:
	statement; //Statement or Group of statement to execute:
	break;     //Optional
	.
	.
	.
	default:    //Default statement
	statement; //Statement or Group of statement to execute:
}


There are some rules for switch Statement that we need to follow:


  • » The Expression used in switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type.
    » We can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.
    » The constant-Expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.
    » When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
    » When a Break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
    » Not every case Needs to contain a break. if no break appears, the flow of control will fall through to subsequent cases until a break is reached.
    » A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the case is true. No break is needed in the default case.



Example:

Let's have an example to clear the concept of Switch Statement. in this example we will create an Program. this Program will ask Student to Enter their Grade. When student will enter their Grade, then our program will show comment about the Grade. so let's start.



As we know that C++ is case sensitive programming language. so "A" and "a" will be two different grades in the switch statement. if case constant-expression is "A" and user Enter "a" then Switch statement will execute default statement, because there is no "a" in case constant-expression. to avoid this type of error and allow user to enter capital "A" or small "a", we can put two cases at same time having same statement for both as shown in the given example:



/*Switch Statement Example: - InfoBrother*/
 
#include <iostream>
using namespace std;
main()
{
	char grade; //used to store Grade from user.
 
	cout<<" Enter Your Grade: ( Only A, B, C, and D grades are available:) ";
	cin>>grade;
 
	switch (grade)
	{
    	case 'A': //read note to know about these types of case.
    	case 'a':
    	cout<<" Excellent...!Keep it up:\n "; 
    	break;
 
    	case'B':
    	case'b':
    	cout<<" Good...! Need more care \n";
    	break; 
 
    	case'C':
    	case'c':
    	cout<<" fair...! Need to be careful about your study: \n"; 
    	break;
 
    	case'D':
    	case'd':
    	cout<<" Fail...!!call your parents tomorrow.:\n ";
    	break;
 
   	 	default:
    	cout<<" Only A, B, C, and D grades are avaliable. \n";    
	}
 
	return 0;
}


Copy and paste this code into your compiler and try to play with code. remove "Break" statement to know how its work. put any letter other than A, B, C and D to know how "default" work.



Example:

Let's have another useful Switch Example: in this example we will create an simple calculator which can perform Addition (+), Multiplication (*), Subtraction (-), and Division (/). An Operator will be case constant-expression here. and switch expression work will based on Operator.



/*Simple Calculator. - InfoBrother */
 
#include<iostream>
using namespace std;
main()
{
    float a, b, Result; //a=first Number, b=second Number,
 
    char operation; //will used to store "operator" from user:
    cout<<"\n\nEnter Your Question (e.g 2+3) and press Enter:"<<"\n";
    cout<<"Only(Multiplication,,Addition,,Subtraction and Division):"<<endl;
    cin>>a>>operation>>b; //first-Number operator second-Number (e.g. 2+3)
 
    switch(operation)
    {    
    	case'+': 
        	Result=a+b;
        	break;
    	case'-':
        	Result=a-b;
        	break;
    	case'*':
        	Result=a*b;
        	break;
    	case'/':
        	Result=a/b;
        	break;
 
    	default: // if user enter a wrong thing then this stateme nt will execute.
    	cout<<"Invalid Method...!!Please Use the Method As Shown in Above"<<endl;
    	return -1;
}
    cout<<"Result = " <<Result<<endl;
 
return 0;
}


If-else Vs Switch Statement:

If-else statement is computationally one of the most expensive statements in C++ Programming language. We call it expensive due to the fact that the processor has to go through many cycles to executes an if-else statement to evaluate a Multiway decision. but if we have huge numbers of a condition and need to take some action according to each condition, then if-else statements might be gone expensive. the code will be gone lengthy and less efficient.

The C++ language provides us a stand-alone structure to handle these instances. This structure is "Switch Structure". the switch statement make our code more efficient and easy to read and understand as shown in the example below.



if ( grade == 'A' )                        
        cout <<" Excellent " ;
 
if (grade == 'B')
        cout<<" Very Good";
 
if ( grade == 'C' )
        cout <<" Good " ;
 
if ( grade == 'D' )
        cout << " Poor " ;
 
if ( grade == 'F' )
        cout <<" Fail " ;


Switch ( grade )
{
	case 'A' : cout << " Excellent " ;
	case 'B' : cout << " Very Good " ;
	case 'C' : cout << " Good " ;
	case 'D' : cout << " Poor " ;
	case 'F' : cout << " Fail " ;
}


In the above Example we create a program that will show some comments about Grade when user will enter their grade. We use If-else and switch statement to create this program. both statements will work same. but we can see that "Switch statement" is more efficient and easy to read and understand.



Each case can be followed by any number of statements to execute. Unlike with the if statement, the statements to be executed do not need to be contained in a block with curly braces:







I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





WRITE FOR INFOBROTHER

Advertising






Advertisement