having problem with switch statement !

this the code that i write and it always execute "Error" !

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;
int main()
{
int grade;
cout<<"Enter the number of ur grade";
cin>>grade;
switch (grade)
{
case 1:
if (grade >=90 && grade <= 100)
cout<<"you got A"<<endl;
break;
case 2:
if (grade <=59)
cout<<"you got F"<<endl;
break;
default:
cout<<"Error"<<endl;
}
return 0;
}



and when i entered 95 or 59 it prints Error
plz someone tell me where is my mistake thanks ..
Switch statement is like if statement but when you must put much more ifs then you put in statement. You cant put if in statement, because in your case here reads if grade is 1? because in your case you have case 1:. If you don't need switch statment you can write only this:

if(grade>=90 && grade<=100) cout<<"You got A"<<endl;
else if(grade<=59) cout<<"You got F"<<endl;
else cout<<"ERROR"<<endl;

This will work for you... In you case prints Error because your numbers 95 or 59 it goes to default:.
i want to use it with switch statement because i want it after to put the b,c,d, grades
so i'm going to write it with many if's ..
why does it read case 1 as 1 ! how do i make it to let it read the grade ?
thanks 4 replaying me back ..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;
int main()
{
int grade;
cout<<"Enter the number of ur grade";
cin>>grade;

if (grade >=90 && grade <= 100)
cout<<"you got A"<<endl;

else if (grade <=59)
cout<<"you got F"<<endl;

else
cout<<"Error"<<endl;

return 0;
}


Why isnt this ok
The reason its not working the way you want it to is because it takes the grade and when it equals 1 it will evaluate case 1, when it equals 2 it will evaluate case 2 etc
use Breadman's suggestion.
@ro0ody86 you must put in cases all posible needs for example:

switch(grade)
{
case 1:cout<<"you got F"<<endl;
case 2:cout<<"you got F"<<endl;
..
..
case 59:cout<<"you got F"<<endl;
case 90: cout<<"you got A"<<endl;
case 91: cout<<"you got A"<<endl;
..
..
case 100: cout<<"you got A"<<endl;
default:
cout<<"Error"<<endl;
}
This is very dificult to write if you want,so write it.. :-)
wow !
thanks guys ,but because i wanted to try it with switch statement and it looks so hard way =/
thanks again ..
Topic archived. No new replies allowed.