C# Programing
Fundamentals
Fundamentals
  • C# Fundamental concepts
    • Introduction to C#.NET
    • Variables and Types
    • User Input
    • Strings
    • Methods
    • Date and Time
    • Conditions
    • Loops
    • Arrays
  • Problem based learning
    • P1: Arithmetic Calculator
    • P2: Number Guessing
    • P3: Print Patterns
    • P4: Grade Average
    • P5: Calculate Age
  • Practice Problems
    • W3Schools
    • Edabit
Powered by GitBook
On this page
  1. Problem based learning

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}");
PreviousP3: Print PatternsNextP5: Calculate Age

Last updated 1 year ago