Switch

I have been following Bucky's Tutorial on Youtube and I am up to 25 which is switches.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  #include <iostream>
using namespace std;
int main()
{
int age;
cin >> age;
switch(age)
{

case                // Trying to add more than one number here so it can read 10-20 or something like that

cout <<"It worked!";

}
}
Well, the only way i know how to do it is le Ctrl+c and Ctrl+v way.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
  #include <iostream>
using namespace std;
int main()
{
int age;
cin >> age;
switch(age)
{

case 10: 

cout << "It worked!";
break;

case 11: 

cout << "It worked!";
break;

case 12: 

cout << "It worked!";

case 13: 

cout << "It worked!";
break;

case 14: 
break;

cout << "It worked!";  //and so on

}
return 0; //you didn't forget me, did you?
}
You can have multiple cases execute the same thing:
1
2
3
4
5
6
7
8
9
10
11
12
13
switch(choice){
   case 1:
   case 2:
   case 3:
      cout << "Hi.";
      break;
   case 4:
      cout << "Boo.";
      break;
   default:
      cout << "Blargh.";
      break;
}


It's a quirk of the switch-case statement. If you forget all of your breaks, the program goes into an infinite loop.
So there is no way to do like case 10 - 20 except for adding a new case each time? That is annoying D;. I guess I'll use an If statement instead, and for return 0; you do not need it since the program assumes it will return 0. At least for Code::Blocks anyways.
Last edited on
Just read your Daleth, that seems a little better. Would it make more sense do to something like this. if (10 <= age <= 20)?
Close, but unlike us human's representation for a range, C++ works a little differently:if(10 <= age && age <= 20)
And yes, when it comes to ranges, prefer the good 'ol if-else.
Alright Tyvm!
Topic archived. No new replies allowed.