P4: Grade Average

Grade Average Calculator Program

Console.Write("How many grades would you like to enter? ");
int numberOfGrades = int.Parse(Console.ReadLine());

double[] grades = new double[numberOfGrades];
double total = 0;

for (int i = 0; i < numberOfGrades; i++)
{
    Console.Write($"Enter grade {i + 1}: ");
    grades[i] = double.Parse(Console.ReadLine());
    total += grades[i];
}

double average = total / numberOfGrades;
Console.WriteLine($"The average grade is: {average:F2}");

Explanation

  1. The program starts by asking the user how many grades they want to enter. This number is used to create an array of that size.

  2. It then enters a loop where the user is prompted to enter each grade. Each grade is stored in the array, and its value is added to a total sum.

  3. After all grades are entered, the program calculates the average by dividing the total sum by the number of grades.

  4. Finally, the average grade is displayed, formatted to two decimal places.

This program effectively demonstrates the use of arrays to store a collection of items (grades in this case), along with basic loop usage and arithmetic operations to calculate the average

A variation of the same program

Let us now see a variation of the same program, but with two differences.

  • The grades are hardcoded and

  • we are using for-each loop instead of a classical for loop.

double[] grades = {3.0, 3.5, 4.0};

Console.WriteLine("Given grades are:");
foreach(var grade in grades)
    Console.WriteLine(grade);

double total = 0.0;
foreach(double grade in grades)
    total += grade;

double average = total / grades.Length;
Console.WriteLine($"The average grade is: {average:F2}");

Last updated