+ 1

Switch Case [DOUBT]

I am an absolute novice in programming....but wish to learn. Here is a program I typed using the switch case in C++: #include <iostream> using namespace std; int main() { int age; char gender; cout << "Enter the age...\n"; cin >> age; cout << "Enter the gender...\n"; cin >> gender; switch(age,gender) { case (age<13 && gender==m): cout << "Boy"; break; case (age<13 && gender==f): cout << "Girl"; break; case (age>19 && gender==m): cout << "Man"; break; case (age>19 && gender==f): cout << "Woman"; break; case (age>=13 && age <=19): cout << "Teen"; break; default: cout << "Error"; } return 0; } It is throwing up multiple errors... Please help.

6th May 2017, 4:58 AM
Mukund Sai
Mukund Sai - avatar
2 Respuestas
+ 13
A switch statement can only take one parameter to evaluate for case, and each case can only contain either an integer or a char, instead of Boolean statements. E.g. switch (number) { case 1: //something case 2: //something //and so on } switch (character) { case 'A': //something case 'B': //something } -------------------------------------------------------- In order to evaluate your conditions, you need to do multiple if... else statements. E.g. if (age < 13 && gender == 'M') { // something } else if (age >=13 && gender == 'M') { // something } ------------------------------------------------------- OR, if you still want to do switch, you may nest if... else statements within switch cases. switch (gender) { case 'M' : if (age < 13) { //something } else if (age >= 13) { //something } case 'F' : if (age < 13) { //something } else if (age >= 13) { //something } }
6th May 2017, 5:12 AM
Hatsy Rei
Hatsy Rei - avatar
0
1. switch can only be used to evaluate 1 variable at a time. 2. It can only check for equality. It cannot compare two variables. Solution. Use if else if you want to use condition that depend on multiple variables and want to compare or range-check their values.
6th May 2017, 5:17 AM
Ravi Kumar
Ravi Kumar - avatar