Assigning a Letter Grade to the Average Using else if With C# in Unity

David Little
2 min readApr 19, 2021

--

We are now going to expand upon the grade average calculator and get it to assign a letter grade using else if statements. First, let us take a look at the original script.

Since we want to do letter grades now we will need to define ranges for each and lay down some kind of logic for how we want to follow. It’s good practice to lay things out with pseudo code as comments so that you can see it and move things around until your concept is clear. For this one, mine looks like this…

I’m only going as far as a C grade because, well, this is Sparta.

So we basically want the code to say check the average against these ranges of values and whichever one it matches, assign it the letter for that range. We do that with ‘and’, well && in our statements, like this…

You define one end of the range ‘&&’ then the other end. And, you can see that you define what will be written to the console in Unity in these statements. You can quickly see that you could go wild with categorizing the score ranges if you wanted to include D and E grades as well as plus, minus and normal letter grades. You can easily end up with code that is the equivalent to a few of these connected together in a chain.

The complete script looks like this…

We can now not only calculate new values with source variables. We can compare these variables and create new values based upon them.

--

--