find the average of a range of numbers in csharp

You can find the average of a range of numbers in C# by using a loop to add up all the numbers in the range, and then dividing by the total number of numbers in the range. Here's an example code snippet:

main.cs
double sum = 0;
int count = 0;
int start = 1;
int end = 10;

for (int i = start; i <= end; i++)
{
    sum += i;
    count++;
}

double average = sum / count;
Console.WriteLine("The average of the range {0} to {1} is {2}.", start, end, average);
245 chars
14 lines

In this example, we start by initializing variables for the sum and count of numbers in the range, as well as the start and end values of the range (1 and 10, respectively).

We then use a for loop to iterate over each number in the range, adding it to the running sum and incrementing the count of numbers.

Finally, we calculate the average by dividing the sum by the count and output the result using a Console.WriteLine statement.

related categories

gistlibby LogSnag