C++ switch Statements - Devbhoomi

FREE JOB ALERT & ONLINE TUTORIALS

Hot

Post Top Ad

Saturday 7 October 2017

C++ switch Statements

C++ switch Statements




C++ switch statement is used when you have multiple possibilities for the if statement.
The basic format of switch statement is:
 Syntax:
switch(variable)
{
case 1:
   //execute your code
break;

case n:
   //execute your code
break;

default:
   //execute your code
break;
}
After the end of each block it is necessary to insert a break statement because if the programmers do not use the break statement, all consecutive blocks of codes will get executed from each and every case onwards after matching the case block.

Example of a C++ Program to Demonstrate Switch Statement

Example:
#include <iostream>
using namespace std;

main()
{
    int a;
    cout << "Please enter a no between 1 and 5: " << endl; cin >> a;
    
    switch(a)
    {
    case 1:
    cout << "You chose One" << endl; 
    break;
    
    case 2:
    cout << "You chose Two" << endl; 
    break;

    case 3:
    cout << "You chose Three" << endl; 
    break;

    case 4:
    cout << "You chose Four" << endl; 
    break;

    case 5:
    cout << "You chose Five" << endl; 
    break;

    default :
    cout << "Invalid Choice. Enter a no between 1 and 5" << endl; 
    break;
    }
system("PAUSE");
} 
 
Program Output:
cplusplus-switch
When none of the case is evaluated to true, then default case will be executed, and break statement is not required for default statement.

No comments:

Post a Comment

Post Top Ad