I have been asked to create a mark to grade converter in Windows Form Application.
My code below is from the click of a button. Once a user has input their mark into 'Markbox' and the button is clicked the if statement will run and it will find the correct range of the mark. Then it will display a grade, relevant to the mark in 'Gradelb'.
Below is the code under the button click command. I wanted to condense it down to reduce code line space as well as making it more manageable.
void SubmitBtn_Click(object sender, EventArgs e) {
int mark = int.Parse(Markbox.Text);
if (mark >= 45 && mark <= 50) Gradelb.Text = "A*";
else if (mark >= 40 && mark < 45) Gradelb.Text = "A";
else if (mark >= 35 && mark < 40) Gradelb.Text = "B";
else if (mark >= 30 && mark < 35) Gradelb.Text = "C";
else if (mark >= 25 && mark < 30) Gradelb.Text = "D";
else if (mark >= 20 && mark < 25) Gradelb.Text = "E";
else if (mark >= 0 && mark < 20) Gradelb.Text = "U";
else MessageBox.Show("Please enter a mark between 0-50");
Apologies for any errors or incorrect terminology, I am a new Apprentice employee.
string Gr = new string[] { "A*", "A", "B", "C", "D", "E", "U" };
if(mark >=0 && mark <= 50)
Gradelb.Text = Gr[10 - Math.Max(4, (int)Math.Ceiling(mark/5f))];
else
MessageBox.Show("Please enter a mark between 0-100");
A word of caution: After living a decade of "one-liner"'s life, I can advise you one thing: There is no guarantee that this code will be any more efficient than yours.
Explanation
Since the grades and the marks range they are linked with follow a fixed pattern, I created an array of grades so that I could refer to each grade by array index. Now all I need is a expression that could convert a given number to index.
46-50 => 0
40-45 => 1
and so on...
This can be done by dividing the number by 5 (since that is the group size in your example). So for example dividing 41 by 5 will give you 8.2. Doing a Ceiling()
(which returns nearest greater or equal integer) on it will give 9. Subtracting this value from 10 will give you the index of second group (which is grade A).
Math.Max()
(which returns larger of the two parameters) is simply there to ensure that values which are out of array bounds do not cause an exception. This will be the case when marks are 15 or less.