0% found this document useful (0 votes)
10 views

Lesson SWITCH Stmt

The C++ switch statement allows for executing a block of code based on the value of an integer or character expression, providing a more readable alternative to if...else statements. The switch evaluates the expression once, compares it with case values, and executes the corresponding block of code if a match is found, with optional break and default keywords. The break keyword exits the switch block, preventing further code execution and improving efficiency.

Uploaded by

Amy Bndc Mrtnez
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Lesson SWITCH Stmt

The C++ switch statement allows for executing a block of code based on the value of an integer or character expression, providing a more readable alternative to if...else statements. The switch evaluates the expression once, compares it with case values, and executes the corresponding block of code if a match is found, with optional break and default keywords. The break keyword exits the switch block, preventing further code execution and improving efficiency.

Uploaded by

Amy Bndc Mrtnez
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Programmin 2:

C++ switch..case Statement


The switch statement allows us to execute a block of code among many alternatives.
You can do the same thing with the if...else statement.
NOTE: The Expression must be an INT or CHAR data type.

However, the syntax of the switch statement is much easier to read and write.

This is how it works:


1. The switch expression is evaluated once
2. The value of the expression is compared with the values of each case
3. If there is a match, the associated block of code is executed
4. The break and default keywords are optional, and will be described later in this
chapter

The example below uses the weekday number to display the weekday name

int day = 4;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
}

The break Keyword


 When C++ reaches a break keyword, it breaks out of the switch block.
 This will stop the execution of more code and case testing inside the block.
 When a match is found, and the job is done, it's time for a break. There is no need for more
testing.

A break can save a lot of execution time because it "ignores" the execution of all the rest of the code in
the switch block.

You might also like