Whats wrong with my code? It says that the switch (a) is wrong and is a undeclar
ID: 3800307 • Letter: W
Question
Whats wrong with my code? It says that the switch (a) is wrong and is a undeclarable identifier of 'a'
#include <iostream>
using namespace std;
int main ()
{
switch(a)
{
case 1:
cout << "Got a ONE" << endl;
case 3:
cout << "Got a THREE" << endl;
break;
case 5:
cout << "Got a FIVE" << endl;
break;
case 7:
cout << "Got a SEVEN" << endl;
break;
case 9:
cout << "Got a NINE" << endl;
break;
case (a % 2 == 0):
cout << " Got an EVEN NUMBER" << endl;
break;
case ( a % 2! = 0):
cout << " Got an NON DIGIT" << endl;
break;
default:
cout << " Got an Invalid Number" << endl;
break;
}}
Explanation / Answer
Any variable cannot be used unless it is declared.
ERROR 1: In your code, variable 'a' has not been declared.
To use switch function, variable 'a' must contain some value. The value of the variable can be given statically (or) dynamically.
ERROR 2: variable has no value.
static-value is given by the programmer
dynamic - value is taken from the user.
ERROR 3: variable should not appear in constant-expressions like case (a%2 == 0):
Instead if conditional statements can be used.
Check out the code below, dynamic code.
#include <iostream>
using namespace std;
int main (){
int a;
cout<<"Enter value of a: ";
cin>>a;
switch(a){
case 1:
cout << "Got a ONE" << endl;
break;
case 3:
cout << "Got a THREE" << endl;
break;
case 5:
cout << "Got a FIVE" << endl;
break;
case 7:
cout << "Got a SEVEN" << endl;
break;
case 9:
cout << "Got a NINE" << endl;
break;
default:
if(a%2 == 0)
cout << " Got an EVEN NUMBER" << endl;
else if(a%2 != 0)
cout << " Got an NON DIGIT" << endl;
else
cout << " Got an Invalid Number" << endl;
break;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.