Switch Statement Problem

I'm trying to create a simple program that asks the user for a score between 0-100 and grades them depending on the score.

I'm attempting to use a switch statement, however can a range of values be used for a case? for example rather than say case 10:

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
 #include <iostream>

using namespace std;

int main()
{


int nScore;
cout << "Please enter your score: ";
cin >> nScore;

switch(nScore){
	
	case(WHAT WOULD I WRITE HERE?):
	cout << "With a score between 0-59 you are graded an F."<<endl;
	break;
	default:
		cout << endl;
}

 


system("pause");
return 0;
}


or would I have to nest if statements inside this? still trying to figure out logic in c++ lol.
Last edited on
switch statements work with constant values. You need to use if/else logic.
yeah I thought that's what I might need, ok thanks man.
#include <iostream>

using namespace std;

int main()
{


int nScore;
cout << "Please enter your score: ";
cin >> nScore;


if(nScore >=0 && nScore < 60)
{
cout << "With a score between 0-59 you are graded an E."<<endl;
}
else if (nScore >= 60 && nScore < 70)
{
cout << "With a score between 60-69 you are graded an D."<<endl;
}
else if (nScore >=70 && nScore < 80)
{
cout << "With a score between 70-79 you are graded a C."<<endl;
}
else if (nScore >=80 && nScore < 90)
{
cout << "With a score between 80-89 you are graded a B."<<endl;
}
else if (nScore >=90 && nScore < 101)
{
cout << "With a score between 90-100 you are graded a A."<<endl;
}
else
{
cout << "Please enter a valid score!" << endl;
}

system("pause");
return 0;
}

Ok so this works, is there a more optimized way around this?
Maybe something like:

1
2
3
4
5
6
7
8
9
10

if(score >= 0 && score <= 100) //valid scores
{
    if(score < 60 ) //F
    else if(score < 70) //d
    else if(score< 80) //c
    else if(score < 90) //b
    else if(score <= 100) //a
}
else //invalid scores 


Though you'd have to fill in the blanks.


If you don't really care for checking if its greater than 0

You could do something like:

1
2
3
4
5
6
if(score < 60) //f
else if(score < 70) //d
else if(score < 80) //c
else if(score < 90) //b
else if(score <= 100) //a
else //invalid score (greater than 100) 
Ok that looks a lot cleaner, I'll go with that!

Thanks again everyone.
If you want to use a switch statement with a score from 0-100, you can do something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
	switch (score/10)
	{
		case 10:
		case 9:	cout "A";
			break;
		case 8:	cout "B";
			break;
		case 7:	cout "C";
			break;
		case 6:	cout "D";
			break;
		default:cout "F";
			break;
	}
If you do that way it would probably be best to have 5, 4, 3, 2, 1 , 0 == f and default == invalid score
Or you could check for an invalid score beforehand and then not have to worry about it here.
Topic archived. No new replies allowed.