QUESTION TWO (2)

New Life College awards grades to students in each course based on overall exam scores, which are marked out of 100. Grades are determined as in the table below:

\begin{tabular}{|l|l|}
\hline Exam Score & Grade \\
\hline [tex]$\ \textgreater \ =80$[/tex] & A \\
\hline [tex]$\ \textgreater \ =70$[/tex] but [tex]$\ \textless \ 80$[/tex] & B \\
\hline [tex]$\ \textgreater \ =60$[/tex] but [tex]$\ \textless \ 70$[/tex] & C \\
\hline [tex]$\ \textgreater \ =50$[/tex] but [tex]$\ \textless \ 60$[/tex] & D \\
\hline [tex]$\ \textless \ 50$[/tex] & F \\
\hline
\end{tabular}

Write a [tex]$C++$[/tex] program that takes a student's score in an exam and computes and prints an appropriate grade for the student. The program should output both the course name and the grade on the same line with the appropriate descriptions.



Answer :

Sure! Here is a C++ program that takes a student's score in an exam and computes and prints an appropriate grade for the student along with the course name.

```cpp
#include
#include

using namespace std;

string computeGrade(int score) {
if (score >= 80) {
return "A";
} else if (score >= 70 && score < 80) {
return "B";
} else if (score >= 60 && score < 70) {
return "C";
} else if (score >= 50 && score < 60) {
return "D";
} else {
return "F";
}
}

int main() {
string course_name;
int score;

// Input for the course name and score
cout << "Enter course name: ";
getline(cin, course_name);

cout << "Enter exam score: ";
cin >> score;

// Compute the grade based on the score
string grade = computeGrade(score);

// Output the course name and grade
cout << "Course Name: " << course_name << ", Grade: " << grade << endl;

return 0;
}
```

### Step-by-Step Solution:

1. Include Necessary Libraries:
- `#include `: For input and output operations.
- `#include `: For using the `string` data type.

2. Define a Function to Compute Grade:
- A function `computeGrade(int score)` checks the conditions for grading based on the score and returns the corresponding grade as a string.

3. main() Function Implementation:
- Declare variables `course_name` (string) and `score` (int).
- Prompt the user to enter the course name and read it using `getline(cin, course_name)` to handle spaces in the course name.
- Prompt the user to enter the exam score and read it using `cin >> score`.
- Call the `computeGrade` function to determine the grade based on the score.
- Print the course name and grade on the same line with appropriate descriptions.

4. Conditions for Grades:
- `score >= 80`: Grade is "A".
- `70 <= score < 80`: Grade is "B".
- `60 <= score < 70`: Grade is "C".
- `50 <= score < 60`: Grade is "D".
- `score < 50`: Grade is "F".

5. Output:
- The program outputs the course name and grade in the format: `Course Name: [course_name], Grade: [grade]`.

This program efficiently handles the input and output and implements the grading logic in a clear and concise manner.

Other Questions