Hi
I was just wondering if a switch statement can work without writing each case, for instance:
{ int age;
age=18;
while (age!=0)
{
cout<<"Enter age :"<<endl;
cin>>age;
switch (age)
{
case 0:
break;
case 1:
case 2:
case 3:
case 4:
cout<<"Tricycle"<<endl;
break;
case 5:
case 15:
cout<<"Bicycle"<<endl;
break;
case 16:
case 17:
cout<<"Motorcycle"<<endl;
break;
case 18:
case 100:
cout<<"Motorcar"<<endl;
break;
default:
cout<<"You probably shouldn't be driving"<<endl;
break;
}
}
cout<<"goodbye"<<endl<<endl;
It works only for values specifically entered as a case, for instance if you enter 5 or 15 , it says bicycle, but if you enter anything inbetween it goes to default.
Same with 18 and 100. It can't possibly be that you have to enter
case 19:
case 20:
case 21:
case 22:.......up to 100 to include all possible cases.
I just thought about it ...A function can probably also be used, but I'll try to play around with that when I have more time. It might proof more complicated than just using the if-statements but I'll probably learn something...
This is really interesting!
Just trying to get my mind around it, how does the computer see it..
I tested it and it works perfectly, and I can use it in the future but I don't see why it works, considering how the computer sees it
Basically, (age<5) is like saying if ages < 5 then return the value 1, so keep that thought...
I enter age 24
so (age<5) would be false (0)
(age<16) would be false (0)
(age<18) would be false (0)
(age<101) would be true (1)
Add all those results together gives 1, which is 18 - 100.
Just so your clear, heres another..
I entered age 16.
(age<5) would be false (0)
(age<16) would be false (0)
(age<18) would be true (1)
(age<101) would be true (1)
returning 2, which is 16, 17
Just to extend on that ( I should have included it ), Boolean variables are either True or False, but in memory they are stored as 0 or 1 so when returning True from a function your actually returning the value 1