Explain the concept of switch statement with suitable example.


 A switch statement is a control flow statement in programming that allows the program to execute different actions based on different conditions. It's typically used when you have a single variable that can take on several different values, and you want to perform different actions depending on the value of that variable.

Here's an example of a switch statement in JavaScript:

arduino
let day = 3; switch (day) { case 0: console.log("Sunday"); break; case 1: console.log("Monday"); break; case 2: console.log("Tuesday"); break; case 3: console.log("Wednesday"); break; case 4: console.log("Thursday"); break; case 5: console.log("Friday"); break; case 6: console.log("Saturday"); break; default: console.log("Invalid day"); }

In this example, we have a variable called day that is set to the value 3. The switch statement then evaluates the value of day and executes the corresponding case statement. Since day is equal to 3, the switch statement will execute the case 3 statement, which logs "Wednesday" to the console.

If day had been set to a value other than 0-6, the switch statement would execute the default case, which logs "Invalid day" to the console.

The break keyword is used after each case statement to tell the switch statement to exit and move on to the next line of code outside of the switch statement. Without the break keyword, the switch statement would continue executing the following case statements until it encounters a break statement.

Post a Comment

Previous Post Next Post