JavaScript Switch case

JavaScript Switch case is used to execute a block of statement out of multiple blocks of statements based on a condition. JavaScript switch is a condition-based statement that has multiple conditions but executes only one block at a time.

In switch statement, the switch expression is evaluated only once and then the output is compared with every case mentioned inside the switch block and if the output of expression matches one of the cases then the statement written inside the block of that case is executed. If no case matches then the default case is executed.

JavaScript switch case is used in applications where you have to implement a menu like system in which based on user input certain action is taken.

JavaScript switch: Syntax

The expression which evaluates the condition is written inside the switch(expression), followed by a curly bracket which creates a switch block in which the different cases are defined.

switch(expression)
{
case 1:
    //code
    break;
case 2:
    //code
    break;
default:
}

Based on the value of the expression’s output, one of the many cases gets executed, and then the break statement is called which breaks the execution, and the switch case gets exited.

NOTE: If we do not add the break statement after the code statements in the switch case block, then the interpreter would execute each and every case after the matched case.

JavaScript Switch case: Example

In this example, we are using the switch case and each case executes based on the provided value.

let a = 1; switch (a) { case 1: alert(‘case 1 has been executed’); break; case 2: alert(“case 2 has been executed”); break; case 3: alert(“case 3 has been executed”); break; case 4: alert(“case 4 has been executed”); break; default: alert(“default case executed”); }

In the above example, we have used the break statement to terminate the switch case.

JavaScript Switch Case Example without break

Use of the break statement is optional, if we don’t use it then the switch case does not terminate and executes all the rest of the cases till the end, after the matched case. See the below example:

JavaScript Switch Case Example

Switch Case Example

let a = 2; switch (a) { case 1: alert(‘case 1 has been executed’); case 2: alert(“case 2 has been executed”); case 3: alert(“case 3 has been executed”); case 4: alert(“case 4 has been executed”); default: alert(“default case executed”); }

JavaScript Switch Case Default

The default statement is executed if the switch expression output does not match with any of the given cases.

Switch Default Case Example

    <script>
        let a = 6;
        switch (a)
        {
            case 1: alert('case 1 has been executed');
            case 2:
                alert("case 2 has been executed");
            case 3:
                alert("case 3 has been executed");
            case 4:
                alert("case 4 has been executed");
            default:
                alert("default case executed, no matched case is found");
        }
    </script>
</body>

With this, we have covered the JavaScript switch statement. Although if else statements are popular and used in most of the cases, in some scenarios having using switch statement makes the code more readable and scalable. So choose wisely, what to use when.

C++ switch..case Statement

In this tutorial, we will learn about switch statement and its working in C++ programming with the help of some examples.

The switch statement allows us to execute a block of code among many alternatives.

The syntax of the switch statement in C++ is:

switch (expression)  {
    case constant1:
        // code to be executed if 
        // expression is equal to constant1;
        break;

    case constant2:
        // code to be executed if
        // expression is equal to constant2;
        break;
        .
        .
        .
    default:
        // code to be executed if
        // expression doesn't match any constant
}

How does the switch statement work?

The expression is evaluated once and compared with the values of each case label.

  • If there is a match, the corresponding code after the matching label is executed. For example, if the value of the variable is equal to constant2, the code after case constant2: is executed until the break statement is encountered.
  • If there is no match, the code after default: is executed.

Note: We can do the same thing with the if...else..if ladder. However, the syntax of the switch statement is cleaner and much easier to read and write.


Flowchart of switch Statement

C++ switch...case flowchart
Flowchart of C++ switch…case statement

Example: Create a Calculator using the switch Statement

// Program to build a simple calculator using switch Statement
#include <iostream>
using namespace std;

int main() {
    char oper;
    float num1, num2;
    cout << "Enter an operator (+, -, *, /): ";
    cin >> oper;
    cout << "Enter two numbers: " << endl;
    cin >> num1 >> num2;

    switch (oper) {
        case '+':
            cout << num1 << " + " << num2 << " = " << num1 + num2;
            break;
        case '-':
            cout << num1 << " - " << num2 << " = " << num1 - num2;
            break;
        case '*':
            cout << num1 << " * " << num2 << " = " << num1 * num2;
            break;
        case '/':
            cout << num1 << " / " << num2 << " = " << num1 / num2;
            break;
        default:
            // operator is doesn't match any case constant (+, -, *, /)
            cout << "Error! The operator is not correct";
            break;
    }

    return 0;
}

Run Code

Output 1

Enter an operator (+, -, *, /): +
Enter two numbers: 
2.3
4.5
2.3 + 4.5 = 6.8

Output 2

Enter an operator (+, -, *, /): -
Enter two numbers: 
2.3
4.5
2.3 - 4.5 = -2.2

Output 3

Enter an operator (+, -, *, /): *
Enter two numbers: 
2.3
4.5
2.3 * 4.5 = 10.35

Output 4

Enter an operator (+, -, *, /): /
Enter two numbers: 
2.3
4.5
2.3 / 4.5 = 0.511111

Output 5

Enter an operator (+, -, *, /): ?
Enter two numbers: 
2.3
4.5
Error! The operator is not correct.

In the above program, we are using the switch...case statement to perform addition, subtraction, multiplication, and division.

How This Program Works

Notice that the break statement is used inside each case block. This terminates the switch statement.

If the break statement is not used, all cases after the correct case are executed.

  1. We first prompt the user to enter the desired operator. This input is then stored in the char variable named oper.
  2. We then prompt the user to enter two numbers, which are stored in the float variables num1 and num2.
  3. The switch statement is then used to check the operator entered by the user:
    • If the user enters +, addition is performed on the numbers.
    • If the user enters -, subtraction is performed on the numbers.
    • If the user enters *, multiplication is performed on the numbers.
    • If the user enters /, division is performed on the numbers.
    • If the user enters any other character, the default code is printed.

C switch statement

In this tutorial, you will learn to create the switch statement in C programming with the help of an example.

The switch statement allows us to execute one code block among many alternatives.

You can do the same thing with the if...else..if ladder. However, the syntax of the switch statement is much easier to read and write.


Syntax of switch…case

switch (expression)
​{
    case constant1:
      // statements
      break;

    case constant2:
      // statements
      break;
    .
    .
    .
    default:
      // default statements
}

How does the switch statement work?

The expression is evaluated once and compared with the values of each case label.

  • If there is a match, the corresponding statements after the matching label are executed. For example, if the value of the expression is equal to constant2, statements after case constant2: are executed until break is encountered.
  • If there is no match, the default statements are executed.

If we do not use break, all statements after the matching label are executed.

By the way, the default clause inside the switch statement is optional.


switch Statement Flowchart

Flowchart of switch statement

Example: Simple Calculator

// Program to create a simple calculator
#include <stdio.h>

int main() {
    char operator;
    double n1, n2;

    printf("Enter an operator (+, -, *, /): ");
    scanf("%c", &operator);
    printf("Enter two operands: ");
    scanf("%lf %lf",&n1, &n2);

    switch(operator)
    {
        case '+':
            printf("%.1lf + %.1lf = %.1lf",n1, n2, n1+n2);
            break;

        case '-':
            printf("%.1lf - %.1lf = %.1lf",n1, n2, n1-n2);
            break;

        case '*':
            printf("%.1lf * %.1lf = %.1lf",n1, n2, n1*n2);
            break;

        case '/':
            printf("%.1lf / %.1lf = %.1lf",n1, n2, n1/n2);
            break;

        // operator doesn't match any case constant +, -, *, /
        default:
            printf("Error! operator is not correct");
    }

    return 0;
}

Output

Enter an operator (+, -, *,): -
Enter two operands: 32.5
12.4
32.5 - 12.4 = 20.1

The  operator entered by the user is stored in the operator variable. And, two operands 32.5 and 12.4 are stored in variables n1 and n2 respectively.

Since the operator is -, the control of the program jumps to

printf("%.1lf - %.1lf = %.1lf", n1, n2, n1-n2);

Finally, the break statement terminates the switch statement.