Conditional Statements in c++: Switch

               When you turn on the switch, the appliance started. In  the same way, using your switch case, you can control your variables.

First, the syntax of the switch case is given below…

switch( expression)

{

  case value1 : statements;

                    break;

  case value2 : statements;

                    break;

  ………………………………..

  ………………………………..

 default : statements;

}

Key terms:

‘expression’ : It is a condition or variable which makes the switch as conditional statement.

‘case’ : it is a keyword to identify the choice value.

‘break’ : it is also a keyword which makes a particular block to end after the statement execution.

‘default’ : If none of the value is applicable for any cases, this will be executed.

Let us create an example to find the month name based on the number given.

C++ Program:  

#include <iostream>

using namespace std;

int main() {

int ch;

cout << "Enter your choice from 1 to 12 for printing month names:"<<endl;

cin>>ch;

switch(ch)

{

    case 1: cout<<"Month name: January" <<endl;

            break;

    case 2: cout<<"Month name: February" <<endl;

            break;

    case 3: cout<<"Month name: March" <<endl;

            break;

    case 4: cout<<"Month name: April" <<endl;

            break;

    case 5: cout<<"Month name: May" <<endl;

            break;

    case 6: cout<<"Month name: June" <<endl;

            break;

    case 7: cout<<"Month name: July" <<endl;

            break;

    case 8: cout<<"Month name: August" <<endl;

            break;

    case 9: cout<<"Month name: September" <<endl;

            break;

    case 10: cout<<"Month name: October" <<endl;

            break;

    case 11: cout<<"Month name: November" <<endl;

            break;

    case 12: cout<<"Month name: December" <<endl;

            break;

    default: cout<<"There is no such month exists"<<endl;

}       

    return 0;

}

Output:

Enter your choice from 1 to 12 for printing month names:

5

Month name: May

Enter your choice from 1 to 12 for printing month names:

23

There is no such month exists

Hope, you understood the concept. If you have any doubts, post me in the comment box. Keep coding!!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

How to write your first XML program?

Java NIO examples to illustrate channels and buffers.