Cpp - Statement switch Statements

Introduction

switch statement tests one expression for multiple values to decide which of several blocks of code to execute.

The following switch statement displays a singular or plural ending to the word "bug," depending on how many my_int you have killed:

std::cout << "You have killed " << my_int << " bug"; 
switch (my_int) 
{ 
    case 0: 
          std::cout << "s\n"; 
          break; 
    case 1: 
          std::cout << "\n"; 
          break; 
    default: 
          std::cout << "s\n"; 
} 

The switch expression is the variable my_int.

The two case sections catch different values of my_int.

If the value is 0, the character 's' makes the display text "You have killed 0 my_int" with the trailing s.

If the value is 1, the text is "You have killed 1 bug" with no trailing s.

The default section handles all other values for my_int, displaying "You have killed" followed by the number and the word my_int.

The following code shows how to use switch statement on char value.

Demo

#include <iostream> 

int main() /*from  ww  w . j av  a2 s . co m*/
{ 
    char grade; 
    std::cout << "Enter your letter grade (ABCDF): "; 
    std::cin >> grade; 
    switch (grade) 
    { 
    case 'A': 
           std::cout << "Finally!\n"; 
           break; 
    case 'B':   
           std::cout << "You can do better!\n"; 
           break; 
    case 'C':   
           std::cout << "I'm disappointed in you!\n"; 
           break; 
    case 'D':   
           std::cout << "You're not smart!\n"; 
           break; 
    case 'F':   
           std::cout << "Get out of my sight!\n"; 
           break; 
    default:  
           std::cout << "That's not even a grade!\n"; 
           break; 
    } 
    return 0; 
}

Result

The user is prompted for a letter.

That letter is tested in the switch statement.

Related Topics

Exercise