Exercise
Array of positive and negative numbers
Objetive
Write a C# program to ask the user for 10 real numbers and display the average of the positive ones and the average of the negative ones.
Example Code
using System;
class Program
{
static void Main()
{
double[] numbers = new double[10];
double positiveSum = 0, negativeSum = 0;
int positiveCount = 0, negativeCount = 0;
Console.WriteLine("Please enter 10 real numbers:");
for (int i = 0; i < 10; i++)
{
Console.Write($"Enter number {i + 1}: ");
numbers[i] = Convert.ToDouble(Console.ReadLine());
}
foreach (double num in numbers)
{
if (num > 0)
{
positiveSum += num;
positiveCount++;
}
else if (num < 0)
{
negativeSum += num;
negativeCount++;
}
}
if (positiveCount > 0)
{
double positiveAverage = positiveSum / positiveCount;
Console.WriteLine($"The average of the positive numbers is: {positiveAverage}");
}
else
{
Console.WriteLine("There are no positive numbers.");
}
if (negativeCount > 0)
{
double negativeAverage = negativeSum / negativeCount;
Console.WriteLine($"The average of the negative numbers is: {negativeAverage}");
}
else
{
Console.WriteLine("There are no negative numbers.");
}
}
}