Simple Switch Statement Example Program In C++


Definition of Switch

In C++ programming, the switch statement is a type of selection method used to allow the block of code among many alternatives.Simply, It changes the control flow of program execution, which selects one of the suitable code block from the multiple blocks. 

  • We can use switch statements alternative for an if..else ladder.
  • The switch statement is often faster than nested if...else Ladder.

Syntax

Same like C Syntax,

switch ( <expression> or <variable> ) {
	case value1:
	  //Block 1 Code Here
	  break;

	case value2:
	  //Block 1 Code Here
	  break;
	...

	default:
	  Code to execute for not match case
	  break;
}

Simple Switch Example Program for find Vowels

/* Simple Switch Statement Example Program In C++ */
/* Switch Programs, Find Vowels,Control Programs,C++ Examples */

// Header Files
#include<iostream>
#include<conio.h>

//Main Function

using namespace std;

int main() {
   // Local Variable 'ch' Declaration
   char ch;

   cout << "Simple Switch Statement Example Program\n";

   cout << "Enter the Letter (In Capital Letter): ";
   cin >> ch;

   //Switch Case Check
   switch (ch) {
      case 'A': cout << "Your Character Is A.Your Character is Vowel\n";
         break;

      case 'E': cout << "Your Character Is E.Your Character is Vowel\n";
         break;

      case 'I': cout << "Your Character Is I.Your Character is Vowel\n";
         break;

      case 'O': cout << "Your Character Is O.Your Character is Vowel\n";
         break;

      case 'U': cout << "Your Character Is U.Your Character is Vowel\n";
         break;

      default: cout << "Your Character is Not Vowel.Otherwise Not a Capital Letter\n";
         break;
   }
   // Wait For Output Screen
   getch();

   //Main Function return Statement
   return 0;
}

Sample Output

Simple Switch Statement Example Program
Enter the Letter (In Capital Letter):A
Your Character Is A.Your Character is Vowel

Simple Switch Statement Example Program
Enter the Letter (In Capital Letter): u
Your Character is Not Vowel.Otherwise Not a Capital Letter

Switch Statement Rules in C++

  • A switch works with the char and int data types.
  • It also works with enum types
  • Switch expression/variable datatype and case datatype are should be matched.
  • A switch block has many numbers of case statements, Each case ends with a colon.
  • Each case ends with a break statement. Else all case blocks will execute until a break statement is reached.
  • The switch exists When a break statement is reached, 
  • A switch block has only one number of default case statements, It should end of the switch.
  • The default case block executed when none of the cases is true. 
  • No break is needed in the default case.