Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I convert a series of if statements testing ranges into a switch?


this my if condition code, but I can’t convert it.

    #include <iostream>
using namespace std;
int main()
{
  int num;
  cout << "please enter a number: ";
  cin >> num;

  if (num == 10)
  {
    cout << "Case 1";
  }
  else if (num > 19 && num < 21)
  {
    cout << "Case 2";
  }
  else if (num > 29 && num < 33)
  {
    cout << "Case 3";
  }
  else
  {
    cout << "Invalid Number";
  }
  return 0;
}  

what I tried to do was this:

    switch (num)
{
case 1:
 num==10;
  cout << "Case 1";
  break;
case 2: 
  num > 19 && num < 21;
  cout << "Case 2";
  break;
case 3:
  num> 29 && num < 33;
  cout << "Case 3";
  break;
default:
 cout << "Invalid Number";
}  

it Ignores my condition and if I put my condition in place of "case 1" it gives me an error.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

so , what can I do?

>Solution :

A switch only selects individual values, but you can use case fall-through to let it combine multiple values. In your example, there aren’t that many in the chosen ranges, so it might be appropriate:

switch (num)
{
case 10:
  cout << "Case 1";
  break;
case 20:
  cout << "Case 2";
  break;
case 30:
case 31:
case 32:
  cout << "Case 3";
  break;
default:
 cout << "Invalid Number";
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading