At line 1, grade must be a value from 1 to 6. The generated code will then execute the statements identified by the case label corresponding to that value.
Your statements at lines 4,9,14,19,24,29 don't do anything because they are simply conditions that are evaluated and the results of that evaluation ignored. These statements have nothing to do with the switch statement.
so then how do you make it so it doesn't evaluate the line but choose the line to output the result? I tried putting if statements inside the cases and it didn't do anything either.
how does the computer know what case it needs to pick without the conditions?
Cases are used when you have to perform a simple (if) task but it's a long process. In your case, you shouldn't really use a switch case, I'd rather use an if statement because you have to check multiple things.
Where it says case 1: the '1' will be executed if the integer is '1'. If it's not '1' the switch statement will keep going until it finds something which matches. It is also good to include default: at the end of the cases just in case nothing matches.
Try this:
Ask for a user input from 1 to 5 and create a switch case starting from 1 to 5, and output something else depending on the case.
how does the computer know what case it needs to pick without the conditions?
The value of the variable in the switch() clause determines which branch is chosen.
1 2 3 4 5 6 7 8 9 10 11 12 13
int var = 1;
switch (var)
{
case 1: cout << "The value of var is 1" << endl;
break;
case 2: cout << "The value of var is 2" << endl;
break;
case 3: cout << "The value of var is 3" << endl;
break;
// etc...
}
It makes so much more sense now, but I'll tell you what I am trying to do, I'm just doing practice programs to get the hang of basic stuff and I'm basing what I do off of this
For the first program, he says to trying using if statements or switch statements. So I was trying to switch statement. I personally think if statements would work better too but I just want to know how I could run it with a switch
One way to do this with switch/cases is to use integer division on the numeric grade, assuming 100 will be the highest grade. The default case in a switch statement catches everything that wasn't matches in one of the named cases.
1 2 3 4 5 6 7 8 9
switch (grade/10)
{
case 10: cout << "You got an A+!" << endl;
break;
// case 9 through 6 for grades A through D
default: cout << "You got an F" << endl;
break;
The user doesn't have to enter 1-10. That's the result you get from dividing the grade they did enter by 10. For example - if they enter 95, 95/10 is 9. If they enter 91, 91/10 is still 9. So those both fall into the same case where they get an A.
Edit:
If you wanted to use a range, that would go into an if/else statement structure.