Signup/Sign In

C++ Program To Find A Grade Of Given Numbers Using Switch Case

In this program, we have declared score and grade variables. The score variables will be used to store input from the end-user and the grade variable will store the grade value after finding the grade using an if-else statement. Then we have taken the input value from the end-user and stored it in the score variable.

Now, checked the entered score is valid or not. If the score doesn’t belong to 0 to 100 (inclusive) then it will be treated as invalid score. In that it will display the appropriate message and stop the execution of the program.

If the score is valid then we will start finding the grade based on the given score. From the table, if the score is greater than or equal to 90 then the grade will ‘A’, and so on. For a score lesser than 50 the grade will be ‘F’. Finally, we displayed the grade value on the screen.

Program To Find A Grade Of Given Numbers Using Switch Case In C++

Score in subject Grade
>=90 A
80-89 B
70-79 C
60-69 D
50-59 E
<50 F
#include<iostream>
using namespace std;
// function to find grade using switch-case
char findGrade(int score) 
{
   // check score is valid or not
   // score is valid if it belongs to 0-100
   if(score<0 || score>100) {
     return '\0';
   }

   // find grade for given score
   switch( score / 10 )
   {
     case 10:
     case 9:
       return 'A';
     case 8:
       return 'B';
     case 7:
       return 'C';
     case 6:
       return 'D';
     case 5:
       return 'E';
     default:
       return 'F';
   }
}
// main function
int main()
{
   // variables
   int score;
   char grade;

   // take score
   cout << "Enter score(0-100): ";
   cin >> score;

   // find grade
   grade = findGrade(score);
   
   // display grade
   if(grade=='\0')
     cout << "Invalid Score";
   else
     cout << "Grade = " << grade << endl; 

   return 0;
}

Conclusion

In this program while using function, we didn’t used break statement because whenever we use return statement then control came back to the caller method, and the next statements of called function won’t executed.