Sum of ONLY negative numbers

Viewed 691

C# Loops. I need help with this question:

Write a program that reads 10 data from the keyboard and add only those that are negative.

I just started class in January an we're in C# loops. I haven't been in school for over 3 weeks now because of the coronavirus. So i'm kinda lost now and we just started online class so big rips to me:(

double sum = 0.0d;
double n = 0.0d;

for (int i = 1; i <= 10; i++)
{
    Console.Write($"Enter a number {i}: ");
    n = double.Parse(Console.ReadLine());
}

if (n < 0)
    sum = n + n;

Console.WriteLine($"{sum}");

Here is my code (I'm probably 100% wrong but it's 2am rn and i'm trying);

Thanks! :)

Thank ya'll so much for the help!

3 Answers

Actually, you're closer than you think. You should adjust the sum inside the loop, and it should be adjusted by adding n to the current sum rather than setting it to n + n.

By adjusting after the loop is finished, you only take the last number in to account. And, by setting sum to n + n, the sum you end up with will just be twice the last number entered if it was negative, and zero if not.

In other words, something like:

double sum = 0.0d;
double n = 0.0d;

for (int i = 1; i <= 10; i++)
{
    Console.Write($"Enter a number {i}: ");
    n = double.Parse(Console.ReadLine());
    if (n < 0)
        sum = sum + n;
}

Console.WriteLine($"{sum}");

you are adding to sum outside of your loop ...

move that if into the loop after the assignment of n, add n to sum and not to n and you are good

One possibility to filter for negative numbers is Math.Min(Int,Int) which returns the Minimum of 2 numbers. In this case positive numbers are set to 0. After each iteration your would do this:

sum = sum + Math.Min(0, InputNumber)

Or you can simply use an if clause:

if (InputNumber < 0) { sum = sum + InputNumber }

Note: Your need to add your numbers inside your loop, otherwise it would only be executed once.

Related