The data file datalines.txt contains decimal data, one number per line. Using C#
ID: 3593370 • Letter: T
Question
The data file datalines.txt contains decimal data, one number per line. Using C#, and including comments to understand the implementation, write a program that reads in the data from the datalines.txt file and displays the following statistics about the data:
Count of the data items
Total of the data items
Average of the data items
Maximum value of the data items
Minimum value of the data items.
Download the file dataLab.txt to your project directory.
Remember to initialize variables:
Total should start with 0
Count should start with 0
Maximum should start with Double.NegativeInfinity
Minimum should start with Double.PositiveInfinity
Explanation / Answer
using System;
using System.IO;
namespace test
{
class Program
{
static void Main(string[] args)
{
try
{
double[] numbers = new double[1000]; //initialise array
int index = 0,count=0; //initialise other variables
double max=double.NegativeInfinity,min=double.PositiveInfinity,total=0;
System.IO.StreamReader inputFile; //Declare a StreamReader variable
inputFile = File.OpenText("datalines.txt"); //Open the file and get a StreamReader object.
while (index < numbers.Length && !inputFile.EndOfStream) //Read the file contents into the array.
{
numbers[index] = double.Parse(inputFile.ReadLine()); //dtore file content to array line by line
total+=numbers[index]; //total the double values
index++; //keep track of index
count++; //keeps count of variables
}
for (var i = 0; i < numbers.Length; i++) //find minimum
{
if (min > numbers[i])
min = numbers[i];
}
for (var i = 0; i < numbers.Length; i++) //find maximum
{
if (max < numbers[i])
max = numbers[i];
}
//output the values we found
Console.WriteLine("Total = {0}", total); //display total
Console.WriteLine();
Console.WriteLine("Average = {0}", total/count); //display average
Console.WriteLine();
Console.WriteLine("Minimum = {0}", min); //display minimum
Console.WriteLine();
Console.WriteLine("Maximum = {0}", max); //display maximum
Console.WriteLine();
//Close the file.
inputFile.Close();
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.