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.
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.
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;
case 1: cout << "The value of var is 1" << endl;
case 2: cout << "The value of var is 2" << endl;
case 3: cout << "The value of var is 3" << endl;
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
case 10: cout << "You got an A+!" << endl;
// case 9 through 6 for grades A through D
default: cout << "You got an F" << endl;
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.
If you wanted to use a range, that would go into an if/else statement structure.