Write a C# console app that will input a text file of numbers. For these numbers, find the number of numbers (one per line), the largest of these numbers, the smallest of these number, and the average of these numbers.
Also determine the number of numbers in the range 00000 - 09999, 10000 - 199999, 20000 - 29999, etc. all the way through 90000 - 99999.
using System;
using System.IO;
namespace file_numbers
{
class Program
{
public static void Main(string[] args)
{
int num, count, high, small, sum;
int[] cnt = new int [10];
String line;
Console.Write("Enter filename: ");
string fname = Console.ReadLine();
// Create file with random 500 numbers in the range 0..99999
//---------------------------------------------------------
try
{
StreamWriter sw = new StreamWriter(fname);
Random rnd = new Random();
int value;
for(int i=0;i<500;i++)
{
value = rnd.Next(0, 99999);
sw.WriteLine(value.ToString());
}
sw.Close();
}
catch(Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
//---------------------------------------------------------
// Read text file of numbers
try
{
StreamReader sr = new StreamReader(fname);
count = 0;
sum = 0;
line = sr.ReadLine();
num = Convert.ToInt32(line);
high = num;
small = num;
while (line != null)
{
num = Convert.ToInt32(line);
count++;
sum = sum + num;
if (high < num)
high = num;
if (small > num)
small = num;
cnt[(num / 10000)]++;
line = sr.ReadLine();
}
Console.WriteLine("Number of numbers: {0}", count);
Console.WriteLine("Largest number: {0}", high);
Console.WriteLine("Smallest number: {0}", small);
Console.WriteLine("Average number: {0}", Convert.ToDouble(sum)/Convert.ToDouble(count));
for(int i=0;i<10;i++)
Console.WriteLine("Number of numbers in the range {0} - {1}: {2}", i*10000, ((i+1)*10000)-1, cnt[i]);
sr.Close();
}
catch(Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
Console.Write("\nPress any key to continue . . . ");
Console.ReadKey(true);
}
}
}
Comments
Leave a comment