Objective
Write a C# program to calculate various basic statistical operations: it will accept numbers from the user and display their sum, average, minimum and maximum, as in the following example:
Number? 5
Total=5 Count=1 Average=5 Max=5 Min=5
Number? 2
Total=7 Count=2 Average=3.5 Max=5 Min=2
Number? 0
Goodbye!
(As seen in this example, the program will end when the user enters 0)
Example C# Exercise
Show C# Code
using System; // Importing the System namespace to use Console functionalities
class Program
{
// Main method where the program execution begins
static void Main()
{
double total = 0; // Variable to store the total sum of numbers
int count = 0; // Variable to store the count of entered numbers
double max = double.MinValue; // Initialize max to the smallest possible value
double min = double.MaxValue; // Initialize min to the largest possible value
while (true)
{
// Prompt the user to enter a number
Console.Write("Number? ");
double number = double.Parse(Console.ReadLine()); // Read the number and parse it to double
// If the user enters 0, break out of the loop and end the program
if (number == 0)
{
Console.WriteLine("Goodbye!");
break;
}
// Update total, count, max, and min
total += number;
count++;
if (number > max)
{
max = number; // Update max if the current number is greater
}
if (number < min)
{
min = number; // Update min if the current number is smaller
}
// Calculate the average
double average = total / count;
// Display the statistics
Console.WriteLine($"Total={total} Count={count} Average={average} Max={max} Min={min}");
}
}
}
Output
Case 1:
Number? 10
Total=10 Count=1 Average=10 Max=10 Min=10
Number? 5
Total=15 Count=2 Average=7.5 Max=10 Min=5
Number? 20
Total=35 Count=3 Average=11.666666666666666 Max=20 Min=5
Number? 0
Goodbye!
Case 2:
Number? -5
Total=-5 Count=1 Average=-5 Max=-5 Min=-5
Number? -10
Total=-15 Count=2 Average=-7.5 Max=-5 Min=-10
Number? 0
Goodbye!
Case 3:
Number? 3.5
Total=3.5 Count=1 Average=3.5 Max=3.5 Min=3.5
Number? 0
Goodbye!