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();
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
sellimenes
  • 49
  • 8
  • You can sort the array, then display the first one – maccettura Dec 12 '18 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. – René Vogt Dec 12 '18 at 19:07
  • Can you provide one of the ways you have tried? Learning why your approach didn't work may be a valuable experience – eye_am_groot Dec 12 '18 at 19:07
  • 1
    Please post a minimal, complete, and verifiable example of your code. – nicomp Dec 12 '18 at 19:07
  • Thank you for the answer firstly. But I don't need smallest number, I need the first negative number in the array. If I understood you wrong, sorry – sellimenes Dec 12 '18 at 19:08
  • 1
    @nicomp You can use a [magic link](https://meta.stackexchange.com/questions/92060/add-data-se-style-magic-links-to-comments) to automatically link to the MCVE docs. Use `[mcve]` in your comment. –  Dec 12 '18 at 19:08
  • @CPrecius Does "first negative number in an array" mean that the array `{0, 4, -1, 8, -204}` should return `-1` and not `-204`? Or the first negative number you happen to come across in a given array? – Chris Akridge Dec 12 '18 at 19:10
  • `Console.WriteLine(numbers.First(n => n < 0));` – itsme86 Dec 12 '18 at 19:17
  • @itsme86 -- why are you putting an answer in a comment? – Hogan Dec 12 '18 at 19:20
  • 1
    @Hogan Because I don't feel like fleshing it out into a good answer. – itsme86 Dec 12 '18 at 19:20

5 Answers5

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);
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
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);
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
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();
Hogan
  • 69,564
  • 10
  • 76
  • 117
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();
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
Miamy
  • 2,162
  • 3
  • 15
  • 32
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; 
            }
        }
    }
Jon Vote
  • 604
  • 5
  • 17