Calculate a grade average
Calculate the average of a non-empty set of numeric grades without losing the fractional part.
Course progress
Problem 68 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
grades = [78, 85, 91, 84]
Expected output
84.5
What is happening?
The grades total 338. Dividing by four grades gives 84.5.
Solution strategy
Build the right mental model
Add the grades in a double accumulator and divide by the number of grades.
Core concepts
arrays · floating-point arithmetic
Complexity
Time O(n), space O(1).
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for calculate-grade-average
using System;
class Program
{
static double GradeAverage(double[] grades)
{
if (grades.Length == 0) throw new ArgumentException("At least one grade is required.");
double total = 0;
foreach (double grade in grades) total += grade;
return total / grades.Length;
}
static void Main()
{
Console.WriteLine(GradeAverage(new[] { 78.0, 85.0, 91.0, 84.0 }).ToString("0.0"));
}
}Knowledge check
Questions students often ask
What is the main idea behind calculate a grade average?
Add the grades in a double accumulator and divide by the number of grades.
What is the time and space complexity of this solution?
Time O(n), space O(1).
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.