Back to Course

Introduction to C++

0% Complete
0/0 Steps
  1. C++: Basics
    5Topics
    |
    6 Quizzes
  2. C++: Compilation and Execution
    5Topics
    |
    6 Quizzes
  3. C++: Variables
    9Topics
    |
    10 Quizzes
  4. C++: Conditions Operators
    5Topics
    |
    6 Quizzes
  5. C++: Logical Operators
    3Topics
    |
    4 Quizzes
  6. C++: Loops and Errors
    8Topics
    |
    9 Quizzes
  7. C++: Vectors
    4Topics
    |
    3 Quizzes
Lesson 4, Topic 5
In Progress

C++: Switch Statement

Yasin Cakal 9 Nov 2021
Lesson Progress
0% Complete

Now we know how to write programs providing different outputs based on the inputs. However, such programs are so commonly used in C++ that we have a special switch statement for them. It is more like a shortcut to if else, else if, and else statements.

This is a time-saving alternative to the if else, else if, and else statements. We write switch (variable). The variable added is the one we want to put under various conditions to give different outputs. Let’s practice this through a program to recognize who the number extension belongs to.

#include <iostream>

int
main ()
{
  int num;
  std::cout << "Which number do you want to dial?\n" << "I want to dial: \n";
  std::cin >> num;
  switch (num)
    {
    case 1:
      std::cout << "This is the operator's number.";
      break;
    case 2:
      std::cout << "This is the customer service.";
      break;
    case 3:
      std::cout << "This is the manager's number.";
      break;
    case 4:
      std::cout << "This is the elevator service man's number.";
      break;
    default:
      std::cout << "Invalid number. Make sure your entry is correct";

    }
}

Output:

Which number do you want to dial?
I want to dial: 
3
This is the manager's number.

Let’s understand this code:

  • The num added, followed by switch, is the variable we are putting under different conditions for different outputs.
  • case is used to mention the condition for the executor to enter the first statement. Our code says case 1:, which means in case the user enters 1, the output This is the operator's number. will be given.
  • break; is entered to ensure that no other case is excuted. switch statements are slightly different from if else statements in this case. If break; is not added in the code, the program will execute all the cases, including the default code.
  • Then the second case is added with its condition. If the entered number by the user is 2, this condition is satisfied this part of the program is executed.
  • At the end, we have default. This is executed in case no other condition is satisfied. In this case, if the input by the user is 22, the default would be executed.

Responses

Leave a Reply

%d bloggers like this: