Introduction
In this lab, we will write a C++ program that will take an input score from the end-user and then find the grade based on the given score using the switch case statement.
In this lab, we will write a C++ program that will take an input score from the end-user and then find the grade based on the given score using the switch case statement.
First, we need to create a new file named grade.cpp
in the ~/project
directory. We will use the touch editor to create the file with the following command:
touch ~/project/grade.cpp
Add the following code to the grade.cpp
file:
#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;
}
Save the changes to the grade.cpp
file and exit the editor. To compile the code, run the following command in the terminal:
g++ ~/project/grade.cpp -o grade && ./grade
The above command will compile the code and create an executable file named grade
. The ./grade
command is used to run the executable file and execute it.
If everything is done correctly, you will see the following output in the terminal:
Enter score(0-100):
Type in a score and press enter, and you should see an output similar to the following:
Grade = A
In this lab, we created a C++ program to find the grade based on the score using the switch case statement. We learned how to take input from the end-user and then effectively use the switch case statement to calculate the corresponding grade.