0% found this document useful (0 votes)
27 views5 pages

C++ Switch Case Control Structure Guide

Uploaded by

2022478618
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Topics covered

  • Data Types,
  • C++,
  • Variable Declaration,
  • Error Handling,
  • Syntax,
  • Control Flow,
  • Control Statements,
  • Programming Logic,
  • Default Case,
  • User Input
0% found this document useful (0 votes)
27 views5 pages

C++ Switch Case Control Structure Guide

Uploaded by

2022478618
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Topics covered

  • Data Types,
  • C++,
  • Variable Declaration,
  • Error Handling,
  • Syntax,
  • Control Flow,
  • Control Statements,
  • Programming Logic,
  • Default Case,
  • User Input

C++ Lab Module

Lan

Lab 5.2

Control Structure – Selection (Continue)

Switch Case

The switch statement allows us to execute one code block among many alternatives.
It is similar to if...else..if, however, the syntax of the switch statement is
much easier to read and write.

Syntax:

switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

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 x, statements after
case x are executed until break is encountered. If there is no match, the default
statements are executed.

1
C++ Lab Module
Lan

Flowchart Represent Switch Case:

Figure 1: Flowchart for Switch Case

2
C++ Lab Module
Lan

Example 1:

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;
default:
cout << “The day does not EXIST!!”;
}

Output:

Thursday

Change the day = 10 and observe what happen.

3
C++ Lab Module
Lan

Example 2:
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:
cout << "Error! The operator is not correct";
break;
}
}

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

4
C++ Lab Module
Lan

Exercise:

1. Write a program with Switch Case statement to determine which college a student is
placed based on his/her college code. If the code is between 1 and 4, the student is
Non-Resident.

College Code College


1 Mawar
2 Perindu
3 Delima
4 Kenanga

2. Convert the following if..else statement to a Switch Case statement.

int main()
{
int number;
cout << "Enter an integer: ";
cin >> number;

if (number == 1 )
{
cout << "You are eligible for a 10% discount << endl;
}
else if (number == 2)
{
cout << "You are eligible for a 50% discount << endl;
}
else
{
cout << "No Discount.";
}
}

Common questions

Powered by AI

Switch case statements are limited because they only work with discrete, single-variable expressions, typically of integral or enumeration types. They cannot handle complex conditions or comparisons involving multiple variables or logical operators, where if...else constructs excel. Hence, for scenarios needing intricate condition checks, if...else statements are more versatile and suitable .

Fall-through behavior in a switch statement occurs when execution moves from one case to the next without encountering a "break" statement. This happens because, without "break", control simply continues to the next line of code. Fall-through can be controlled by explicitly using "break" statements at the end of each case block to terminate execution within the switch statement, thus ensuring that only the matched case code executes .

The program can be structured as follows: "int collegeCode; cout << "Enter college code: "; cin >> collegeCode; switch (collegeCode) { case 1: cout << "Mawar"; break; case 2: cout << "Perindu"; break; case 3: cout << "Delima"; break; case 4: cout << "Kenanga"; break; default: cout << "The student is non-resident"; }" This uses the college code to determine the corresponding college name .

C++ switch statements cannot directly handle string values due to their requirement for integral type expressions, unlike if...else if statements that can natively compare strings with equality operators. To mimic switch behavior for strings, one might use a mapping function to convert strings into integer keys or employ a series of if...else if clauses to compare string values directly .

The default case in a switch statement handles situations where none of the specified cases match the evaluated expression. It acts as a catch-all to ensure that the switch statement handles unexpected or invalid inputs gracefully, providing a fallback action that prevents the program from executing unexpected or undefined behavior. This is crucial for robustness and error-handling in code .

If a variable passed to a switch statement does not match any of the defined case values, and if the default case is present, the code within the default case block is executed. Otherwise, the switch statement completes without performing any action, leading to potentially unhandled conditions .

When an expression value matches one of the case labels in a switch statement, the program control jumps directly to the matched case label and executes the corresponding block of code. Execution continues until a "break" statement is encountered, which then exits the switch statement to prevent fall-through into subsequent case blocks. For instance, in the example where "int day = 4;" and the switch statement is used to print days of the week, the expression matches with "case 4:", and "Thursday" is printed. The break statement then stops execution, preventing further cases from being executed .

To convert an if...else statement into a switch case, one must have a discrete and enumerable condition. For instance, for checking specific numbers that yield different discount messages, the if...else statement: "if (number == 1) { cout << "10% discount"; } else if (number == 2) { cout << "50% discount"; } else { cout << "No Discount"; }" can be converted to: "switch (number) { case 1: cout << "10% discount"; break; case 2: cout << "50% discount"; break; default: cout << "No Discount"; }" This uses the same logical conditions with a clear separation per case .

Handling exceptions, specifically for division to prevent division by zero, involves incorporating conditional checks within the corresponding case of the switch statement. For example, before performing the division under the '/' case, a preliminary check "if (num2 != 0)" should be included to ensure the divisor is not zero. Otherwise, an error message should be returned. More robust exception handling could include using try-catch blocks around the switch statement to catch exceptions like divide-by-zero or invalid operators .

Switch statements provide a clearer and more concise syntax compared to if...else statements, especially when dealing with multiple conditions that depend on a single variable or expression. They make the code easier to read and maintain as they group all related outcomes together under case labels. Switch statements also improve performance in some cases, as they evaluate the expression once and use direct jumps to execute the matched case block .

You might also like