C# How To Find The Average Of 10 Numbers Using A While Loop
To find the average of 10 numbers using a while loop in C#, you can follow these steps:
- Initialize variables to keep track of the sum and count of numbers.
- Use a while loop to read 10 numbers from the user or any other source.
- Add each number to the sum and increment the count.
- After the loop, calculate the average by dividing the sum by the count.
Here's a C# program that demonstrates this:
using System;
class Program
{
static void Main()
{
int count = 0; // Initialize count to 0
double sum = 0; // Initialize sum to 0
// Use a while loop to read 10 numbers
while (count < 10)
{
Console.Write("Enter a number: ");
if (double.TryParse(Console.ReadLine(), out double number))
{
sum += number; // Add the number to the sum
count++; // Increment the count
}
else
{
Console.WriteLine("Invalid input. Please enter a valid number.");
}
}
// Calculate the average
double average = sum / 10;
// Display the average
Console.WriteLine($"The average of the 10 numbers is: {average}");
}
}
This program will keep prompting the user to enter a number until 10 valid numbers have been entered. It then calculates the average of these numbers and displays it to the user.