Skip to content
Advertisement

Is this qualified as a switch statement?

I have to use this as a switch statement. This is a switch statement, right?

    if (dGrade > 93.99) {strFGrade= strA;}                              //A= above 94

    else if (dGrade >= 90.00 && dGrade <= 93.99 ) {strFGrade= strLA;}   //A- = 90-93.99

    else if (dGrade >= 87.70 && dGrade <= 89.99)  {strFGrade= strHB;}   //B+= 87.7-89.99

    else if (dGrade >= 83.33 && dGrade <= 87.69)  {strFGrade= strB;}    //B= 83.33-87.69

    else if (dGrade >= 80.00 && dGrade <= 83.32 ) {strFGrade= strLB;}   //B- = 80-83.32

    else if (dGrade >= 75.00 && dGrade <= 79.99 ) {strFGrade= strHC;}   //C+= 75-79.99

    else if (dGrade >= 70.00 && dGrade <= 74.99 ) {strFGrade= strC;}    //C= 70-74.99

    else if (dGrade >= 60.00 && dGrade <= 69.99 ) {strFGrade= strD;}    //D=60-69.99

    else    {strFGrade= strF;}                                          //F= below 60

Advertisement

Answer

No, it’s not possible to test if a value lies in an interval like this with a switch-statement. Switch-statements have one branch for each individual value of a type, and the branch is taken if the value being switch on is equal to that of the branch.

That being said, it is possible to write your code in a bit more compact way like this:

if      (dGrade >= 94.00) strFGrade = strA;
else if (dGrade >= 90.00) strFGrade = strLA; 
else if (dGrade >= 87.70) strFGrade = strHB; 
else if (dGrade >= 83.33) strFGrade = strB;  
else if (dGrade >= 80.00) strFGrade = strLB; 
else if (dGrade >= 75.00) strFGrade = strHC; 
else if (dGrade >= 70.00) strFGrade = strC;  
else if (dGrade >= 60.00) strFGrade = strD;  
else strFGrade = strF;

The trick here is that you can leave out half of the tests because you have already tested that in an earlier if-statement. This does not take into account that values could lie between the limits of two different intervals in the original code.

The blocks (with { and }) are also not necessary here.

And note the conventional white space usage, with space on both sides of the =.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement