148k views
4 votes
Convert the following conditional statement to switch statement:

if (numBooks >=0 && numBooks <=2) cout << "You earned 0 points.\\"; else if (numBooks == 4) cout << "You earned 5 points.\\"; else cout << "That's an invalid number of books.\\";

User Dr Deo
by
7.1k points

1 Answer

4 votes

Final answer:

To convert the given conditional statement to a switch statement, follow these steps: identify the condition, create a switch statement, add cases for each value, include code for each case, and add a default case. Here's the converted switch statement.

Step-by-step explanation:

To convert the given conditional statement to a switch statement, you can use the following steps:

  1. Identify the condition in each if statement and assign it to a variable.
  2. Create a switch statement with the variable as the expression.
  3. Add cases for each possible value of the variable.
  4. Include the appropriate code for each case.
  5. Add a default case for any values that don't match the cases.

Here's the converted switch statement:

switch (numBooks) {
case 0:
case 1:
case 2:
cout << "You earned 0 points.\\";
break;
case 4:
cout << "You earned 5 points.\\";
break;
default:
cout << "That's an invalid number of books.\\";
}

User Midhun
by
8.4k points