3

I am just new in programming so excuse me for this 'easy' question.

I have a array list which have negative and positive numbers. It's in C#. I want to write on console, first negative number in this array list. How can do it? I tried a few things but it's writing all negative numbers or only the last negative number. I can't write the first one. Can anyone help me, please?

Here is my example of code :

int[] numbers = new int[] {13, 22, -5, 94, 66, -38, 41, -79, -1, 53};
int[] firstminus = new int[1];    

for (int i = 0; i < 10; i++)
{
    if (numbers[i] < 0)
        firstminus[0] = numbers[i];
}

Console.WriteLine(firstminus[0]);
Console.ReadLine();
10
  • You can sort the array, then display the first one Commented Dec 12, 2018 at 19:05
  • 3
    Welcome to StackOverflow! There are a lot of ways to accomplish that, but I think you would learn nothng if someone provides these complete solutions here. It would be better to show what you have tried, so we could spot the mistakes you made. Commented Dec 12, 2018 at 19:07
  • 1
    Please post a minimal, complete, and verifiable example of your code. Commented Dec 12, 2018 at 19:07
  • 1
    @nicomp You can use a magic link to automatically link to the MCVE docs. Use [mcve] in your comment. Commented Dec 12, 2018 at 19:08
  • 1
    @Hogan Because I don't feel like fleshing it out into a good answer. Commented Dec 12, 2018 at 19:20

5 Answers 5

4

To correct your attempt add a break after you found the number. That will terminate the loop and you'll have the first negative number in the array.

for (int i = 0; i < 10; i++)
{
    if (numbers[i] < 0) 
    {
        firstminus[0] = numbers[i];
        break;
    }
}

Notice 2 things:

  • There is no need for an array firstminus - better just have it a simple int.
  • The loop runs to 10. This is a magic number. Instead run until array's length. Please take the time to read this: What is a magic number, and why is it bad?

So:

int firstMinus;
for (int i = 0; i < numbers.Length; i++)
{
    if (numbers[i] < 0) 
    {
        firstminus = numbers[i];
        break;
    }
}

And last, if you are familiar with linq then just use .FirstOrDefault which returns the first item in the collection that matches a predicate (or the default of the type if none meet the predicate):

var firstMinus = numbers.FirstOrDefault(i => i < 0);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for that detaily explanation. I understood my fault and I learned news. I am so glad.
2

You're close, you'll just need to break as soon as you find the first negative number. i.e.

if (numbers[i] < 0) {
     firstminus[0] = numbers[i];
     break; // terminate the loop
}

btw, I'd use an int variable instead of constructing an array to store the result.

i.e.

int firstminus = 0;
for (int i = 0; i < numbers.Length; i++)
{
   if (numbers[i] < 0) {
      firstminus = numbers[i];
      break; // terminate the loop
   }
}

on another note, the simplest way would be via LINQ:

numbers.FirstOrDefault(x => x < 0);

1 Comment

IMHO - this is a better answer than mine :).
1

I would use a while loop -- it just makes sense for the problem.

Also -- remember the use case where there is no neg -- you have to handle that too.

int[] numbers = new int[] {13, 22, -5, 94, 66, -38, 41, -79, -1, 53};
int index = 0

while (index < numbers.Length & numbers[index] >= 0)
 index++;


if (index < numbers.Length & numbers[index] < 0)
    Console.WriteLine(numbers[index]);
else 
    Console.WriteLing("No neg.");

    Console.ReadLine();

2 Comments

Hmm I didn't even think about while loops, thanks a lot
@CPrecius -- next time think of the poor forgotten while loop! It gets to much competition from foreach and linq!
0
int[] numbers = new int[] {13, 22, -5, 94, 66, -38, 41, -79, -1, 53};

for (int i = 0; i < 10; i++)
{
    if (numbers[i] < 0)
    {
        Console.WriteLine(numbers[i]);
        break;
    }     
}
Console.ReadLine();

Comments

0

A 'better' solution is to use linq:

int[] numbers = new int[] { 13, 22, -5, 94, 66, -38, 41, -79, -1, 53 };
int[] firstminus = new int[1];
firstminus[0] = numbers.FirstOrDefault(n => n < 0);

Update - in response to Gilad Green's comment about performance - great point! When I run the following, I find that the loop actually performs about 1/2 second faster on my box:

    static void Main(string[] args)
    {
        var stopWatch = new Stopwatch(); 
        Console.WriteLine("Linq method");
        stopWatch.Start();
        for (var i = 0; i < 10000000; i++)
        {
            LinqMethod(); 
        }
        stopWatch.Stop();
        Console.WriteLine($"Elapsed time: {stopWatch.Elapsed}");
        stopWatch.Reset();

        Console.WriteLine("Loop method");
        stopWatch.Start();
        for (var i = 0; i < 10000000; i++)
        {
            LoopMethod();
        }
        stopWatch.Stop();
        Console.WriteLine($"Elapsed time: {stopWatch.Elapsed}");

        Console.ReadLine();
    }

    private static void LinqMethod()
    {
        int[] numbers = new int[] { 13, 22, -5, 94, 66, -38, 41, -79, -1, 53 };
        int[] firstminus = new int[1];
        firstminus[0] = numbers.FirstOrDefault(n => n < 0);
    }

    private static void LoopMethod()
    {
        int[] numbers = new int[] { 13, 22, -5, 94, 66, -38, 41, -79, -1, 53 };
        int[] firstminus = new int[1];
        for (int i = 0; i < 10; i++)
        {
            if (numbers[i] < 0)
            {
                firstminus[0] = numbers[i];
                break; 
            }
        }
    }

4 Comments

I'd say it's worth explaining why linq is "better" :)
Yeah good point. Well it avoids a loop, it's less code and it's more 'C#-ish'. It should perform better.
best to add it properly to the answer. (about performance I wouldn't say so.. it probably compiles to very similar code in this case)
@GiladGreen - You make a great point. In fact - on my box the loop runs faster than linq. See updated code above.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.